]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Apply refactoring from cargo clippy
[rust.git] / src / items.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 // Formatting top-level items - functions, structs, enums, traits, impls.
12
13 use std::cmp::min;
14
15 use syntax::{abi, ast, ptr, symbol};
16 use syntax::ast::ImplItem;
17 use syntax::codemap::{BytePos, Span};
18
19 use {Indent, Shape, Spanned};
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
22               recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
23 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
24 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
25            rewrite_call_inner, ExprType};
26 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
27             ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
28 use rewrite::{Rewrite, RewriteContext};
29 use types::join_bounds;
30 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
31             format_constness, format_defaultness, format_mutability, format_unsafety,
32             format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
33             last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, stmt_expr,
34             trim_newlines, trimmed_last_line_width, wrap_str};
35 use vertical::rewrite_with_alignment;
36 use visitor::FmtVisitor;
37
38 fn type_annotation_separator(config: &Config) -> &str {
39     colon_spaces(
40         config.space_before_type_annotation(),
41         config.space_after_type_annotation_colon(),
42     )
43 }
44
45 // Statements of the form
46 // let pat: ty = init;
47 impl Rewrite for ast::Local {
48     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
49         debug!(
50             "Local::rewrite {:?} {} {:?}",
51             self,
52             shape.width,
53             shape.indent
54         );
55
56         skip_out_of_file_lines_range!(context, self.span);
57
58         if contains_skip(&self.attrs) {
59             return None;
60         }
61
62         let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
63         let mut result = if attrs_str.is_empty() {
64             "let ".to_owned()
65         } else {
66             try_opt!(combine_strs_with_missing_comments(
67                 context,
68                 &attrs_str,
69                 "let ",
70                 mk_sp(
71                     self.attrs.last().map(|a| a.span.hi()).unwrap(),
72                     self.span.lo(),
73                 ),
74                 shape,
75                 false,
76             ))
77         };
78
79         // 4 = "let ".len()
80         let pat_shape = try_opt!(shape.offset_left(4));
81         // 1 = ;
82         let pat_shape = try_opt!(pat_shape.sub_width(1));
83         let pat_str = try_opt!(self.pat.rewrite(context, pat_shape));
84         result.push_str(&pat_str);
85
86         // String that is placed within the assignment pattern and expression.
87         let infix = {
88             let mut infix = String::with_capacity(32);
89
90             if let Some(ref ty) = self.ty {
91                 let separator = type_annotation_separator(context.config);
92                 let indent = shape.indent + last_line_width(&result) + separator.len();
93                 // 1 = ;
94                 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
95                 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
96
97                 infix.push_str(separator);
98                 infix.push_str(&rewrite);
99             }
100
101             if self.init.is_some() {
102                 infix.push_str(" =");
103             }
104
105             infix
106         };
107
108         result.push_str(&infix);
109
110         if let Some(ref ex) = self.init {
111             // 1 = trailing semicolon;
112             let nested_shape = try_opt!(shape.sub_width(1));
113
114             result = try_opt!(rewrite_assign_rhs(context, result, ex, nested_shape));
115         }
116
117         result.push(';');
118         Some(result)
119     }
120 }
121
122 // TODO convert to using rewrite style rather than visitor
123 // TODO format modules in this style
124 #[allow(dead_code)]
125 struct Item<'a> {
126     keyword: &'static str,
127     abi: String,
128     vis: Option<&'a ast::Visibility>,
129     body: Vec<BodyElement<'a>>,
130     span: Span,
131 }
132
133 impl<'a> Item<'a> {
134     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
135         let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
136             "extern".into()
137         } else {
138             format!("extern {}", fm.abi)
139         };
140         Item {
141             keyword: "",
142             abi: abi,
143             vis: None,
144             body: fm.items
145                 .iter()
146                 .map(|i| BodyElement::ForeignItem(i))
147                 .collect(),
148             span: span,
149         }
150     }
151 }
152
153 enum BodyElement<'a> {
154     // Stmt(&'a ast::Stmt),
155     // Field(&'a ast::Field),
156     // Variant(&'a ast::Variant),
157     // Item(&'a ast::Item),
158     ForeignItem(&'a ast::ForeignItem),
159 }
160
161 impl<'a> FmtVisitor<'a> {
162     fn format_item(&mut self, item: Item) {
163         self.buffer.push_str(&item.abi);
164         self.buffer.push_str(" ");
165
166         let snippet = self.snippet(item.span);
167         let brace_pos = snippet.find_uncommented("{").unwrap();
168
169         self.buffer.push_str("{");
170         if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
171             // FIXME: this skips comments between the extern keyword and the opening
172             // brace.
173             self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
174             self.block_indent = self.block_indent.block_indent(self.config);
175
176             if item.body.is_empty() {
177                 self.format_missing_no_indent(item.span.hi() - BytePos(1));
178                 self.block_indent = self.block_indent.block_unindent(self.config);
179
180                 self.buffer
181                     .push_str(&self.block_indent.to_string(self.config));
182             } else {
183                 for item in &item.body {
184                     self.format_body_element(item);
185                 }
186
187                 self.block_indent = self.block_indent.block_unindent(self.config);
188                 self.format_missing_with_indent(item.span.hi() - BytePos(1));
189             }
190         }
191
192         self.buffer.push_str("}");
193         self.last_pos = item.span.hi();
194     }
195
196     fn format_body_element(&mut self, element: &BodyElement) {
197         match *element {
198             BodyElement::ForeignItem(item) => self.format_foreign_item(item),
199         }
200     }
201
202     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
203         let item = Item::from_foreign_mod(fm, span, self.config);
204         self.format_item(item);
205     }
206
207
208     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
209         let rewrite = item.rewrite(&self.get_context(), self.shape());
210         self.push_rewrite(item.span(), rewrite);
211         self.last_pos = item.span.hi();
212     }
213
214     pub fn rewrite_fn(
215         &mut self,
216         indent: Indent,
217         ident: ast::Ident,
218         fd: &ast::FnDecl,
219         generics: &ast::Generics,
220         unsafety: ast::Unsafety,
221         constness: ast::Constness,
222         defaultness: ast::Defaultness,
223         abi: abi::Abi,
224         vis: &ast::Visibility,
225         span: Span,
226         block: &ast::Block,
227     ) -> Option<String> {
228         let context = self.get_context();
229
230         let block_snippet = self.snippet(mk_sp(block.span.lo(), block.span.hi()));
231         let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
232             !context.config.fn_empty_single_line();
233         let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
234
235         let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
236             &context,
237             indent,
238             ident,
239             fd,
240             generics,
241             unsafety,
242             constness,
243             defaultness,
244             abi,
245             vis,
246             span,
247             newline_brace,
248             has_body,
249             true,
250         ));
251
252         if force_newline_brace {
253             newline_brace = true;
254         } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
255             !result.contains('\n')
256         {
257             newline_brace = false;
258         }
259
260         // Prepare for the function body by possibly adding a newline and
261         // indent.
262         // FIXME we'll miss anything between the end of the signature and the
263         // start of the body, but we need more spans from the compiler to solve
264         // this.
265         if newline_brace {
266             result.push('\n');
267             result.push_str(&indent.to_string(self.config));
268         } else {
269             result.push(' ');
270         }
271
272         self.single_line_fn(&result, block).or_else(|| Some(result))
273     }
274
275     pub fn rewrite_required_fn(
276         &mut self,
277         indent: Indent,
278         ident: ast::Ident,
279         sig: &ast::MethodSig,
280         span: Span,
281     ) -> Option<String> {
282         // Drop semicolon or it will be interpreted as comment.
283         let span = mk_sp(span.lo(), span.hi() - BytePos(1));
284         let context = self.get_context();
285
286         let (mut result, _) = try_opt!(rewrite_fn_base(
287             &context,
288             indent,
289             ident,
290             &sig.decl,
291             &sig.generics,
292             sig.unsafety,
293             sig.constness.node,
294             ast::Defaultness::Final,
295             sig.abi,
296             &ast::Visibility::Inherited,
297             span,
298             false,
299             false,
300             false,
301         ));
302
303         // Re-attach semicolon
304         result.push(';');
305
306         Some(result)
307     }
308
309     fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
310         if fn_str.contains('\n') {
311             return None;
312         }
313
314         let codemap = self.get_context().codemap;
315
316         if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
317             self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
318         {
319             return Some(format!("{}{{}}", fn_str));
320         }
321
322         if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
323             let rewrite = {
324                 if let Some(stmt) = block.stmts.first() {
325                     match stmt_expr(stmt) {
326                         Some(e) => {
327                             let suffix = if semicolon_for_expr(&self.get_context(), e) {
328                                 ";"
329                             } else {
330                                 ""
331                             };
332
333                             format_expr(&e, ExprType::Statement, &self.get_context(), self.shape())
334                                 .map(|s| s + suffix)
335                                 .or_else(|| Some(self.snippet(e.span)))
336                         }
337                         None => stmt.rewrite(&self.get_context(), self.shape()),
338                     }
339                 } else {
340                     None
341                 }
342             };
343
344             if let Some(res) = rewrite {
345                 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
346                 if !res.contains('\n') && width <= self.config.max_width() {
347                     return Some(format!("{}{{ {} }}", fn_str, res));
348                 }
349             }
350         }
351
352         None
353     }
354
355     pub fn visit_enum(
356         &mut self,
357         ident: ast::Ident,
358         vis: &ast::Visibility,
359         enum_def: &ast::EnumDef,
360         generics: &ast::Generics,
361         span: Span,
362     ) {
363         let enum_header = format_header("enum ", ident, vis);
364         self.buffer.push_str(&enum_header);
365
366         let enum_snippet = self.snippet(span);
367         let brace_pos = enum_snippet.find_uncommented("{").unwrap();
368         let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
369         let generics_str = format_generics(
370             &self.get_context(),
371             generics,
372             "{",
373             "{",
374             self.config.item_brace_style(),
375             enum_def.variants.is_empty(),
376             self.block_indent,
377             mk_sp(span.lo(), body_start),
378             last_line_width(&enum_header),
379         ).unwrap();
380         self.buffer.push_str(&generics_str);
381
382         self.last_pos = body_start;
383
384         self.block_indent = self.block_indent.block_indent(self.config);
385         let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
386         match variant_list {
387             Some(ref body_str) => self.buffer.push_str(body_str),
388             None => if contains_comment(&enum_snippet[brace_pos..]) {
389                 self.format_missing_no_indent(span.hi() - BytePos(1))
390             } else {
391                 self.format_missing(span.hi() - BytePos(1))
392             },
393         }
394         self.block_indent = self.block_indent.block_unindent(self.config);
395
396         if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
397             self.buffer
398                 .push_str(&self.block_indent.to_string(self.config));
399         }
400         self.buffer.push_str("}");
401         self.last_pos = span.hi();
402     }
403
404     // Format the body of an enum definition
405     fn format_variant_list(
406         &self,
407         enum_def: &ast::EnumDef,
408         body_lo: BytePos,
409         body_hi: BytePos,
410     ) -> Option<String> {
411         if enum_def.variants.is_empty() {
412             return None;
413         }
414         let mut result = String::with_capacity(1024);
415         result.push('\n');
416         let indentation = self.block_indent.to_string(self.config);
417         result.push_str(&indentation);
418
419         let items = itemize_list(
420             self.codemap,
421             enum_def.variants.iter(),
422             "}",
423             |f| if !f.node.attrs.is_empty() {
424                 f.node.attrs[0].span.lo()
425             } else {
426                 f.span.lo()
427             },
428             |f| f.span.hi(),
429             |f| self.format_variant(f),
430             body_lo,
431             body_hi,
432             false,
433         );
434
435         let shape = self.shape().sub_width(2).unwrap();
436         let fmt = ListFormatting {
437             tactic: DefinitiveListTactic::Vertical,
438             separator: ",",
439             trailing_separator: self.config.trailing_comma(),
440             separator_place: SeparatorPlace::Back,
441             shape: shape,
442             ends_with_newline: true,
443             preserve_newline: true,
444             config: self.config,
445         };
446
447         let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
448         result.push_str(&list);
449         result.push('\n');
450         Some(result)
451     }
452
453     // Variant of an enum.
454     fn format_variant(&self, field: &ast::Variant) -> Option<String> {
455         if contains_skip(&field.node.attrs) {
456             let lo = field.node.attrs[0].span.lo();
457             let span = mk_sp(lo, field.span.hi());
458             return Some(self.snippet(span));
459         }
460
461         let context = self.get_context();
462         let indent = self.block_indent;
463         let shape = self.shape();
464         let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
465         let lo = field
466             .node
467             .attrs
468             .last()
469             .map_or(field.span.lo(), |attr| attr.span.hi());
470         let span = mk_sp(lo, field.span.lo());
471
472         let variant_body = match field.node.data {
473             ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
474                 // FIXME: Should limit the width, as we have a trailing comma
475                 try_opt!(format_struct(
476                     &context,
477                     "",
478                     field.node.name,
479                     &ast::Visibility::Inherited,
480                     &field.node.data,
481                     None,
482                     field.span,
483                     indent,
484                     Some(self.config.struct_variant_width()),
485                 ))
486             }
487             ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
488                 let one_line_width =
489                     field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
490                 if one_line_width <= shape.width {
491                     format!("{} = {}", field.node.name, self.snippet(expr.span))
492                 } else {
493                     format!(
494                         "{}\n{}{}",
495                         field.node.name,
496                         shape
497                             .indent
498                             .block_indent(self.config)
499                             .to_string(self.config),
500                         self.snippet(expr.span)
501                     )
502                 }
503             } else {
504                 String::from(field.node.name.to_string())
505             },
506         };
507
508         let attrs_extendable = attrs_str.is_empty() ||
509             (context.config.attributes_on_same_line_as_variant() &&
510                 is_attributes_extendable(&attrs_str));
511         combine_strs_with_missing_comments(
512             &context,
513             &attrs_str,
514             &variant_body,
515             span,
516             shape,
517             attrs_extendable,
518         )
519     }
520 }
521
522 pub fn format_impl(
523     context: &RewriteContext,
524     item: &ast::Item,
525     offset: Indent,
526     where_span_end: Option<BytePos>,
527 ) -> Option<String> {
528     if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
529         let mut result = String::with_capacity(128);
530         let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
531         let indent_str = offset.to_string(context.config);
532         let sep = format!("\n{}", &indent_str);
533         result.push_str(&ref_and_type);
534
535         let where_budget = if result.contains('\n') {
536             context.config.max_width()
537         } else {
538             context
539                 .config
540                 .max_width()
541                 .checked_sub(last_line_width(&result))
542                 .unwrap_or(0)
543         };
544         let option = WhereClauseOption::snuggled(&ref_and_type);
545         let where_clause_str = try_opt!(rewrite_where_clause(
546             context,
547             &generics.where_clause,
548             context.config.item_brace_style(),
549             Shape::legacy(where_budget, offset.block_only()),
550             context.config.where_density(),
551             "{",
552             where_span_end,
553             self_ty.span.hi(),
554             option,
555         ));
556
557         // If there is no where clause, we may have missing comments between the trait name and
558         // the opening brace.
559         if generics.where_clause.predicates.is_empty() {
560             if let Some(hi) = where_span_end {
561                 match recover_missing_comment_in_span(
562                     mk_sp(self_ty.span.hi(), hi),
563                     Shape::indented(offset, context.config),
564                     context,
565                     last_line_width(&result),
566                 ) {
567                     Some(ref missing_comment) if !missing_comment.is_empty() => {
568                         result.push_str(missing_comment);
569                     }
570                     _ => (),
571                 }
572             }
573         }
574
575         if try_opt!(is_impl_single_line(
576             context,
577             items,
578             &result,
579             &where_clause_str,
580             item,
581         )) {
582             result.push_str(&where_clause_str);
583             if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
584                 result.push_str(&format!("{}{{{}}}", &sep, &sep));
585             } else {
586                 result.push_str(" {}");
587             }
588             return Some(result);
589         }
590
591         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
592             result.push('\n');
593             let width = offset.block_indent + context.config.tab_spaces() - 1;
594             let where_indent = Indent::new(0, width);
595             result.push_str(&where_indent.to_string(context.config));
596         }
597         result.push_str(&where_clause_str);
598
599         match context.config.item_brace_style() {
600             _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
601             BraceStyle::AlwaysNextLine => result.push_str(&sep),
602             BraceStyle::PreferSameLine => result.push(' '),
603             BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
604                 result.push_str(&sep);
605             } else {
606                 result.push(' ');
607             },
608         }
609
610         result.push('{');
611
612         let snippet = context.snippet(item.span);
613         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
614
615         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
616             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
617             visitor.block_indent = offset.block_only().block_indent(context.config);
618             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
619
620             visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
621             for item in items {
622                 visitor.visit_impl_item(item);
623             }
624
625             visitor.format_missing(item.span.hi() - BytePos(1));
626
627             let inner_indent_str = visitor.block_indent.to_string(context.config);
628             let outer_indent_str = offset.block_only().to_string(context.config);
629
630             result.push('\n');
631             result.push_str(&inner_indent_str);
632             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
633             result.push('\n');
634             result.push_str(&outer_indent_str);
635         }
636
637         if result.chars().last().unwrap() == '{' {
638             result.push_str(&sep);
639         }
640         result.push('}');
641
642         Some(result)
643     } else {
644         unreachable!();
645     }
646 }
647
648 fn is_impl_single_line(
649     context: &RewriteContext,
650     items: &[ImplItem],
651     result: &str,
652     where_clause_str: &str,
653     item: &ast::Item,
654 ) -> Option<bool> {
655     let snippet = context.snippet(item.span);
656     let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
657
658     Some(
659         context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n') &&
660             result.len() + where_clause_str.len() <= context.config.max_width() &&
661             !contains_comment(&snippet[open_pos..]),
662     )
663 }
664
665 fn format_impl_ref_and_type(
666     context: &RewriteContext,
667     item: &ast::Item,
668     offset: Indent,
669 ) -> Option<String> {
670     if let ast::ItemKind::Impl(
671         unsafety,
672         polarity,
673         defaultness,
674         ref generics,
675         ref trait_ref,
676         ref self_ty,
677         _,
678     ) = item.node
679     {
680         let mut result = String::with_capacity(128);
681
682         result.push_str(&format_visibility(&item.vis));
683         result.push_str(format_defaultness(defaultness));
684         result.push_str(format_unsafety(unsafety));
685         result.push_str("impl");
686
687         let lo = context.codemap.span_after(item.span, "impl");
688         let hi = match *trait_ref {
689             Some(ref tr) => tr.path.span.lo(),
690             None => self_ty.span.lo(),
691         };
692         let shape = try_opt!(generics_shape_from_config(
693             context.config,
694             Shape::indented(offset + last_line_width(&result), context.config),
695             0,
696         ));
697         let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
698         let generics_str = try_opt!(rewrite_generics_inner(
699             context,
700             generics,
701             shape,
702             one_line_budget,
703             mk_sp(lo, hi),
704         ));
705
706         let polarity_str = if polarity == ast::ImplPolarity::Negative {
707             "!"
708         } else {
709             ""
710         };
711
712         if let Some(ref trait_ref) = *trait_ref {
713             let result_len = result.len();
714             if let Some(trait_ref_str) = rewrite_trait_ref(
715                 context,
716                 trait_ref,
717                 offset,
718                 &generics_str,
719                 true,
720                 polarity_str,
721                 result_len,
722             ) {
723                 result.push_str(&trait_ref_str);
724             } else {
725                 let generics_str = try_opt!(rewrite_generics_inner(
726                     context,
727                     generics,
728                     shape,
729                     0,
730                     mk_sp(lo, hi),
731                 ));
732                 result.push_str(&try_opt!(rewrite_trait_ref(
733                     context,
734                     trait_ref,
735                     offset,
736                     &generics_str,
737                     false,
738                     polarity_str,
739                     result_len,
740                 )));
741             }
742         } else {
743             result.push_str(&generics_str);
744         }
745
746         // Try to put the self type in a single line.
747         // ` for`
748         let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
749         let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
750             // If there is no where clause adapt budget for type formatting to take space and curly
751             // brace into account.
752             match context.config.item_brace_style() {
753                 BraceStyle::AlwaysNextLine => 0,
754                 _ => 2,
755             }
756         } else {
757             0
758         };
759         let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
760         // 1 = space before the type.
761         let budget = context
762             .config
763             .max_width()
764             .checked_sub(used_space + 1)
765             .unwrap_or(0);
766         if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
767             if !self_ty_str.contains('\n') {
768                 if trait_ref.is_some() {
769                     result.push_str(" for ");
770                 } else {
771                     result.push(' ');
772                 }
773                 result.push_str(&self_ty_str);
774                 return Some(result);
775             }
776         }
777
778         // Couldn't fit the self type on a single line, put it on a new line.
779         result.push('\n');
780         // Add indentation of one additional tab.
781         let new_line_offset = offset.block_indent(context.config);
782         result.push_str(&new_line_offset.to_string(context.config));
783         if trait_ref.is_some() {
784             result.push_str("for ");
785         }
786         let budget = context.config.max_width() - last_line_width(&result);
787         let type_offset = match context.config.where_style() {
788             Style::Legacy => new_line_offset + trait_ref_overhead,
789             Style::Rfc => new_line_offset,
790         };
791         result.push_str(&*try_opt!(
792             self_ty.rewrite(context, Shape::legacy(budget, type_offset))
793         ));
794         Some(result)
795     } else {
796         unreachable!();
797     }
798 }
799
800 fn rewrite_trait_ref(
801     context: &RewriteContext,
802     trait_ref: &ast::TraitRef,
803     offset: Indent,
804     generics_str: &str,
805     retry: bool,
806     polarity_str: &str,
807     result_len: usize,
808 ) -> Option<String> {
809     // 1 = space between generics and trait_ref
810     let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
811     let shape = Shape::indented(offset + used_space, context.config);
812     if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
813         if !(retry && trait_ref_str.contains('\n')) {
814             return Some(format!(
815                 "{} {}{}",
816                 generics_str,
817                 polarity_str,
818                 &trait_ref_str
819             ));
820         }
821     }
822     // We could not make enough space for trait_ref, so put it on new line.
823     if !retry {
824         let offset = offset.block_indent(context.config);
825         let shape = Shape::indented(offset, context.config);
826         let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
827         Some(format!(
828             "{}\n{}{}{}",
829             generics_str,
830             &offset.to_string(context.config),
831             polarity_str,
832             &trait_ref_str
833         ))
834     } else {
835         None
836     }
837 }
838
839 pub fn format_struct(
840     context: &RewriteContext,
841     item_name: &str,
842     ident: ast::Ident,
843     vis: &ast::Visibility,
844     struct_def: &ast::VariantData,
845     generics: Option<&ast::Generics>,
846     span: Span,
847     offset: Indent,
848     one_line_width: Option<usize>,
849 ) -> Option<String> {
850     match *struct_def {
851         ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
852         ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
853             context,
854             item_name,
855             ident,
856             vis,
857             fields,
858             generics,
859             span,
860             offset,
861         ),
862         ast::VariantData::Struct(ref fields, _) => format_struct_struct(
863             context,
864             item_name,
865             ident,
866             vis,
867             fields,
868             generics,
869             span,
870             offset,
871             one_line_width,
872         ),
873     }
874 }
875
876 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
877     if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
878         item.node
879     {
880         let mut result = String::with_capacity(128);
881         let header = format!(
882             "{}{}trait {}",
883             format_visibility(&item.vis),
884             format_unsafety(unsafety),
885             item.ident
886         );
887
888         result.push_str(&header);
889
890         let body_lo = context.codemap.span_after(item.span, "{");
891
892         let shape = Shape::indented(offset + last_line_width(&result), context.config);
893         let generics_str = try_opt!(rewrite_generics(
894             context,
895             generics,
896             shape,
897             mk_sp(item.span.lo(), body_lo),
898         ));
899         result.push_str(&generics_str);
900
901         let trait_bound_str = try_opt!(rewrite_trait_bounds(
902             context,
903             type_param_bounds,
904             Shape::indented(offset, context.config),
905         ));
906         // If the trait, generics, and trait bound cannot fit on the same line,
907         // put the trait bounds on an indented new line
908         if offset.width() + last_line_width(&result) + trait_bound_str.len() >
909             context.config.comment_width()
910         {
911             result.push('\n');
912             let trait_indent = offset.block_only().block_indent(context.config);
913             result.push_str(&trait_indent.to_string(context.config));
914         }
915         result.push_str(&trait_bound_str);
916
917         let has_body = !trait_items.is_empty();
918
919         let where_density = if (context.config.where_density() == Density::Compressed &&
920             (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
921             (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
922             (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
923                 !result.contains('\n'))
924         {
925             Density::Compressed
926         } else {
927             Density::Tall
928         };
929
930         let where_budget = try_opt!(
931             context
932                 .config
933                 .max_width()
934                 .checked_sub(last_line_width(&result))
935         );
936         let pos_before_where = if type_param_bounds.is_empty() {
937             generics.where_clause.span.lo()
938         } else {
939             type_param_bounds[type_param_bounds.len() - 1].span().hi()
940         };
941         let option = WhereClauseOption::snuggled(&generics_str);
942         let where_clause_str = try_opt!(rewrite_where_clause(
943             context,
944             &generics.where_clause,
945             context.config.item_brace_style(),
946             Shape::legacy(where_budget, offset.block_only()),
947             where_density,
948             "{",
949             None,
950             pos_before_where,
951             option,
952         ));
953         // If the where clause cannot fit on the same line,
954         // put the where clause on a new line
955         if !where_clause_str.contains('\n') &&
956             last_line_width(&result) + where_clause_str.len() + offset.width() >
957                 context.config.comment_width()
958         {
959             result.push('\n');
960             let width = offset.block_indent + context.config.tab_spaces() - 1;
961             let where_indent = Indent::new(0, width);
962             result.push_str(&where_indent.to_string(context.config));
963         }
964         result.push_str(&where_clause_str);
965
966         if generics.where_clause.predicates.is_empty() {
967             let item_snippet = context.snippet(item.span);
968             if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
969                 // 1 = `{`
970                 let comment_hi = body_lo - BytePos(1);
971                 let comment_lo = item.span.lo() + BytePos(lo as u32);
972                 if comment_lo < comment_hi {
973                     match recover_missing_comment_in_span(
974                         mk_sp(comment_lo, comment_hi),
975                         Shape::indented(offset, context.config),
976                         context,
977                         last_line_width(&result),
978                     ) {
979                         Some(ref missing_comment) if !missing_comment.is_empty() => {
980                             result.push_str(missing_comment);
981                         }
982                         _ => (),
983                     }
984                 }
985             }
986         }
987
988         match context.config.item_brace_style() {
989             _ if last_line_contains_single_line_comment(&result) => {
990                 result.push('\n');
991                 result.push_str(&offset.to_string(context.config));
992             }
993             BraceStyle::AlwaysNextLine => {
994                 result.push('\n');
995                 result.push_str(&offset.to_string(context.config));
996             }
997             BraceStyle::PreferSameLine => result.push(' '),
998             BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
999                 (!trait_items.is_empty() || result.contains('\n'))
1000             {
1001                 result.push('\n');
1002                 result.push_str(&offset.to_string(context.config));
1003             } else {
1004                 result.push(' ');
1005             },
1006         }
1007         result.push('{');
1008
1009         let snippet = context.snippet(item.span);
1010         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1011
1012         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1013             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1014             visitor.block_indent = offset.block_only().block_indent(context.config);
1015             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1016
1017             for item in trait_items {
1018                 visitor.visit_trait_item(item);
1019             }
1020
1021             visitor.format_missing(item.span.hi() - BytePos(1));
1022
1023             let inner_indent_str = visitor.block_indent.to_string(context.config);
1024             let outer_indent_str = offset.block_only().to_string(context.config);
1025
1026             result.push('\n');
1027             result.push_str(&inner_indent_str);
1028             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1029             result.push('\n');
1030             result.push_str(&outer_indent_str);
1031         } else if result.contains('\n') {
1032             result.push('\n');
1033         }
1034
1035         result.push('}');
1036         Some(result)
1037     } else {
1038         unreachable!();
1039     }
1040 }
1041
1042 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1043     format!("{};", format_header(item_name, ident, vis))
1044 }
1045
1046 pub fn format_struct_struct(
1047     context: &RewriteContext,
1048     item_name: &str,
1049     ident: ast::Ident,
1050     vis: &ast::Visibility,
1051     fields: &[ast::StructField],
1052     generics: Option<&ast::Generics>,
1053     span: Span,
1054     offset: Indent,
1055     one_line_width: Option<usize>,
1056 ) -> Option<String> {
1057     let mut result = String::with_capacity(1024);
1058
1059     let header_str = format_header(item_name, ident, vis);
1060     result.push_str(&header_str);
1061
1062     let body_lo = context.codemap.span_after(span, "{");
1063
1064     let generics_str = match generics {
1065         Some(g) => try_opt!(format_generics(
1066             context,
1067             g,
1068             "{",
1069             "{",
1070             context.config.item_brace_style(),
1071             fields.is_empty(),
1072             offset,
1073             mk_sp(span.lo(), body_lo),
1074             last_line_width(&result),
1075         )),
1076         None => {
1077             // 3 = ` {}`, 2 = ` {`.
1078             let overhead = if fields.is_empty() { 3 } else { 2 };
1079             if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1080                 !fields.is_empty()) ||
1081                 context
1082                     .config
1083                     .max_width()
1084                     .checked_sub(result.len())
1085                     .unwrap_or(0) < overhead
1086             {
1087                 format!("\n{}{{", offset.block_only().to_string(context.config))
1088             } else {
1089                 " {".to_owned()
1090             }
1091         }
1092     };
1093     // 1 = `}`
1094     let overhead = if fields.is_empty() { 1 } else { 0 };
1095     let max_len = context
1096         .config
1097         .max_width()
1098         .checked_sub(offset.width())
1099         .unwrap_or(0);
1100     if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1101         result.push('\n');
1102         result.push_str(&offset.to_string(context.config));
1103         result.push_str(generics_str.trim_left());
1104     } else {
1105         result.push_str(&generics_str);
1106     }
1107
1108     if fields.is_empty() {
1109         let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1110         if snippet.trim().is_empty() {
1111             // `struct S {}`
1112         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1113             // fix indent
1114             result.push_str(snippet.trim_right());
1115             result.push('\n');
1116             result.push_str(&offset.to_string(context.config));
1117         } else {
1118             result.push_str(&snippet);
1119         }
1120         result.push('}');
1121         return Some(result);
1122     }
1123
1124     // 3 = ` ` and ` }`
1125     let one_line_budget = context
1126         .config
1127         .max_width()
1128         .checked_sub(result.len() + 3 + offset.width())
1129         .unwrap_or(0);
1130     let one_line_budget =
1131         one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1132
1133     let items_str = try_opt!(rewrite_with_alignment(
1134         fields,
1135         context,
1136         Shape::indented(offset, context.config),
1137         mk_sp(body_lo, span.hi()),
1138         one_line_budget,
1139     ));
1140
1141     if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1142         Some(format!("{} {} }}", result, items_str))
1143     } else {
1144         Some(format!(
1145             "{}\n{}{}\n{}}}",
1146             result,
1147             offset
1148                 .block_indent(context.config)
1149                 .to_string(context.config),
1150             items_str,
1151             offset.to_string(context.config)
1152         ))
1153     }
1154 }
1155
1156 fn format_tuple_struct(
1157     context: &RewriteContext,
1158     item_name: &str,
1159     ident: ast::Ident,
1160     vis: &ast::Visibility,
1161     fields: &[ast::StructField],
1162     generics: Option<&ast::Generics>,
1163     span: Span,
1164     offset: Indent,
1165 ) -> Option<String> {
1166     let mut result = String::with_capacity(1024);
1167
1168     let header_str = format_header(item_name, ident, vis);
1169     result.push_str(&header_str);
1170
1171     let body_lo = if fields.is_empty() {
1172         context.codemap.span_after(span, "(")
1173     } else {
1174         fields[0].span.lo()
1175     };
1176     let body_hi = if fields.is_empty() {
1177         context.codemap.span_after(span, ")")
1178     } else {
1179         // This is a dirty hack to work around a missing `)` from the span of the last field.
1180         let last_arg_span = fields[fields.len() - 1].span;
1181         if context.snippet(last_arg_span).ends_with(')') {
1182             last_arg_span.hi()
1183         } else {
1184             context
1185                 .codemap
1186                 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1187         }
1188     };
1189
1190     let where_clause_str = match generics {
1191         Some(generics) => {
1192             let budget = context.budget(last_line_width(&header_str));
1193             let shape = Shape::legacy(budget, offset);
1194             let g_span = mk_sp(span.lo(), body_lo);
1195             let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1196             result.push_str(&generics_str);
1197
1198             let where_budget = context.budget(last_line_width(&result));
1199             let option = WhereClauseOption::new(true, false);
1200             try_opt!(rewrite_where_clause(
1201                 context,
1202                 &generics.where_clause,
1203                 context.config.item_brace_style(),
1204                 Shape::legacy(where_budget, offset.block_only()),
1205                 Density::Compressed,
1206                 ";",
1207                 None,
1208                 body_hi,
1209                 option,
1210             ))
1211         }
1212         None => "".to_owned(),
1213     };
1214
1215     if fields.is_empty() {
1216         // 3 = `();`
1217         let used_width = last_line_used_width(&result, offset.width()) + 3;
1218         if used_width > context.config.max_width() {
1219             result.push('\n');
1220             result.push_str(&offset
1221                 .block_indent(context.config)
1222                 .to_string(context.config))
1223         }
1224         result.push('(');
1225         let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1226         if snippet.is_empty() {
1227             // `struct S ()`
1228         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1229             result.push_str(snippet.trim_right());
1230             result.push('\n');
1231             result.push_str(&offset.to_string(context.config));
1232         } else {
1233             result.push_str(&snippet);
1234         }
1235         result.push(')');
1236     } else {
1237         // 3 = `();`
1238         let body = try_opt!(
1239             rewrite_call_inner(
1240                 context,
1241                 "",
1242                 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1243                 span,
1244                 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1245                 context.config.fn_call_width(),
1246                 false,
1247             ).ok()
1248         );
1249         result.push_str(&body);
1250     }
1251
1252     if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1253         (result.contains('\n') ||
1254             offset.block_indent + result.len() + where_clause_str.len() + 1 >
1255                 context.config.max_width())
1256     {
1257         // We need to put the where clause on a new line, but we didn't
1258         // know that earlier, so the where clause will not be indented properly.
1259         result.push('\n');
1260         result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1261             .to_string(context.config));
1262     }
1263     result.push_str(&where_clause_str);
1264
1265     Some(result)
1266 }
1267
1268 pub fn rewrite_type_alias(
1269     context: &RewriteContext,
1270     indent: Indent,
1271     ident: ast::Ident,
1272     ty: &ast::Ty,
1273     generics: &ast::Generics,
1274     vis: &ast::Visibility,
1275     span: Span,
1276 ) -> Option<String> {
1277     let mut result = String::with_capacity(128);
1278
1279     result.push_str(&format_visibility(vis));
1280     result.push_str("type ");
1281     result.push_str(&ident.to_string());
1282
1283     // 2 = `= `
1284     let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1285     let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1286     let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1287     result.push_str(&generics_str);
1288
1289     let where_budget = try_opt!(
1290         context
1291             .config
1292             .max_width()
1293             .checked_sub(last_line_width(&result))
1294     );
1295     let option = WhereClauseOption::snuggled(&result);
1296     let where_clause_str = try_opt!(rewrite_where_clause(
1297         context,
1298         &generics.where_clause,
1299         context.config.item_brace_style(),
1300         Shape::legacy(where_budget, indent),
1301         context.config.where_density(),
1302         "=",
1303         Some(span.hi()),
1304         generics.span.hi(),
1305         option,
1306     ));
1307     result.push_str(&where_clause_str);
1308     if where_clause_str.is_empty() {
1309         result.push_str(" = ");
1310     } else {
1311         result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1312     }
1313
1314     let line_width = last_line_width(&result);
1315     // This checked_sub may fail as the extra space after '=' is not taken into account
1316     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1317     let budget = context
1318         .config
1319         .max_width()
1320         .checked_sub(indent.width() + line_width + ";".len())
1321         .unwrap_or(0);
1322     let type_indent = indent + line_width;
1323     // Try to fit the type on the same line
1324     let ty_str = try_opt!(
1325         ty.rewrite(context, Shape::legacy(budget, type_indent))
1326             .or_else(|| {
1327                 // The line was too short, try to put the type on the next line
1328
1329                 // Remove the space after '='
1330                 result.pop();
1331                 let type_indent = indent.block_indent(context.config);
1332                 result.push('\n');
1333                 result.push_str(&type_indent.to_string(context.config));
1334                 let budget = try_opt!(
1335                     context
1336                         .config
1337                         .max_width()
1338                         .checked_sub(type_indent.width() + ";".len())
1339                 );
1340                 ty.rewrite(context, Shape::legacy(budget, type_indent))
1341             })
1342     );
1343     result.push_str(&ty_str);
1344     result.push_str(";");
1345     Some(result)
1346 }
1347
1348 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1349     (
1350         if config.space_before_type_annotation() {
1351             " "
1352         } else {
1353             ""
1354         },
1355         if config.space_after_type_annotation_colon() {
1356             " "
1357         } else {
1358             ""
1359         },
1360     )
1361 }
1362
1363 pub fn rewrite_struct_field_prefix(
1364     context: &RewriteContext,
1365     field: &ast::StructField,
1366 ) -> Option<String> {
1367     let vis = format_visibility(&field.vis);
1368     let type_annotation_spacing = type_annotation_spacing(context.config);
1369     Some(match field.ident {
1370         Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1371         None => format!("{}", vis),
1372     })
1373 }
1374
1375 fn rewrite_struct_field_type(
1376     context: &RewriteContext,
1377     last_line_width: usize,
1378     field: &ast::StructField,
1379     spacing: &str,
1380     shape: Shape,
1381 ) -> Option<String> {
1382     let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1383     field
1384         .ty
1385         .rewrite(context, ty_shape)
1386         .map(|ty| format!("{}{}", spacing, ty))
1387 }
1388
1389 impl Rewrite for ast::StructField {
1390     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1391         rewrite_struct_field(context, self, shape, 0)
1392     }
1393 }
1394
1395 pub fn rewrite_struct_field(
1396     context: &RewriteContext,
1397     field: &ast::StructField,
1398     shape: Shape,
1399     lhs_max_width: usize,
1400 ) -> Option<String> {
1401     if contains_skip(&field.attrs) {
1402         let span = context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi()));
1403         return wrap_str(span, context.config.max_width(), shape);
1404     }
1405
1406     let type_annotation_spacing = type_annotation_spacing(context.config);
1407     let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1408
1409     let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1410     let attrs_extendable = attrs_str.is_empty() ||
1411         (context.config.attributes_on_same_line_as_field() && is_attributes_extendable(&attrs_str));
1412     let missing_span = if field.attrs.is_empty() {
1413         mk_sp(field.span.lo(), field.span.lo())
1414     } else {
1415         mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1416     };
1417     let mut spacing = String::from(if field.ident.is_some() {
1418         type_annotation_spacing.1
1419     } else {
1420         ""
1421     });
1422     // Try to put everything on a single line.
1423     let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1424         context,
1425         &attrs_str,
1426         &prefix,
1427         missing_span,
1428         shape,
1429         attrs_extendable,
1430     ));
1431     let overhead = last_line_width(&attr_prefix);
1432     let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1433     for _ in 0..lhs_offset {
1434         spacing.push(' ');
1435     }
1436     // In this extreme case we will be missing a space betweeen an attribute and a field.
1437     if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1438         spacing.push(' ');
1439     }
1440     let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1441     if let Some(ref ty) = ty_rewritten {
1442         if !ty.contains('\n') {
1443             return Some(attr_prefix + ty);
1444         }
1445     }
1446
1447     // We must use multiline.
1448     let last_line_width = last_line_width(&prefix);
1449     let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1450
1451     let type_offset = shape.indent.block_indent(context.config);
1452     let rewrite_type_in_next_line = || {
1453         field
1454             .ty
1455             .rewrite(context, Shape::indented(type_offset, context.config))
1456     };
1457
1458     let field_str = match ty_rewritten {
1459         // If we start from the next line and type fits in a single line, then do so.
1460         Some(ref ty) => match rewrite_type_in_next_line() {
1461             Some(ref new_ty) if !new_ty.contains('\n') => format!(
1462                 "{}\n{}{}",
1463                 prefix,
1464                 type_offset.to_string(context.config),
1465                 &new_ty
1466             ),
1467             _ => prefix + ty,
1468         },
1469         _ => {
1470             let ty = try_opt!(rewrite_type_in_next_line());
1471             format!(
1472                 "{}\n{}{}",
1473                 prefix,
1474                 type_offset.to_string(context.config),
1475                 &ty
1476             )
1477         }
1478     };
1479     combine_strs_with_missing_comments(
1480         context,
1481         &attrs_str,
1482         &field_str,
1483         missing_span,
1484         shape,
1485         attrs_extendable,
1486     )
1487 }
1488
1489 pub fn rewrite_static(
1490     prefix: &str,
1491     vis: &ast::Visibility,
1492     ident: ast::Ident,
1493     ty: &ast::Ty,
1494     mutability: ast::Mutability,
1495     expr_opt: Option<&ptr::P<ast::Expr>>,
1496     offset: Indent,
1497     span: Span,
1498     context: &RewriteContext,
1499 ) -> Option<String> {
1500     let colon = colon_spaces(
1501         context.config.space_before_type_annotation(),
1502         context.config.space_after_type_annotation_colon(),
1503     );
1504     let prefix = format!(
1505         "{}{} {}{}{}",
1506         format_visibility(vis),
1507         prefix,
1508         format_mutability(mutability),
1509         ident,
1510         colon,
1511     );
1512     // 2 = " =".len()
1513     let ty_str = try_opt!(ty.rewrite(
1514         context,
1515         try_opt!(
1516             Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1517         ),
1518     ));
1519
1520     if let Some(expr) = expr_opt {
1521         let lhs = format!("{}{} =", prefix, ty_str);
1522         // 1 = ;
1523         let remaining_width = context.config.max_width() - offset.block_indent - 1;
1524         rewrite_assign_rhs(
1525             context,
1526             lhs,
1527             expr,
1528             Shape::legacy(remaining_width, offset.block_only()),
1529         ).and_then(|res| {
1530             recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1531         })
1532             .map(|s| if s.ends_with(';') { s } else { s + ";" })
1533     } else {
1534         Some(format!("{}{};", prefix, ty_str))
1535     }
1536 }
1537
1538 pub fn rewrite_associated_type(
1539     ident: ast::Ident,
1540     ty_opt: Option<&ptr::P<ast::Ty>>,
1541     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1542     context: &RewriteContext,
1543     indent: Indent,
1544 ) -> Option<String> {
1545     let prefix = format!("type {}", ident);
1546
1547     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1548         // 2 = ": ".len()
1549         let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1550         let bounds: &[_] = ty_param_bounds;
1551         let bound_str = try_opt!(
1552             bounds
1553                 .iter()
1554                 .map(|ty_bound| ty_bound.rewrite(context, shape))
1555                 .collect::<Option<Vec<_>>>()
1556         );
1557         if !bounds.is_empty() {
1558             format!(": {}", join_bounds(context, shape, &bound_str))
1559         } else {
1560             String::new()
1561         }
1562     } else {
1563         String::new()
1564     };
1565
1566     if let Some(ty) = ty_opt {
1567         let ty_str = try_opt!(ty.rewrite(
1568             context,
1569             Shape::legacy(
1570                 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1571                 indent.block_only(),
1572             ),
1573         ));
1574         Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1575     } else {
1576         Some(format!("{}{};", prefix, type_bounds_str))
1577     }
1578 }
1579
1580 pub fn rewrite_associated_impl_type(
1581     ident: ast::Ident,
1582     defaultness: ast::Defaultness,
1583     ty_opt: Option<&ptr::P<ast::Ty>>,
1584     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1585     context: &RewriteContext,
1586     indent: Indent,
1587 ) -> Option<String> {
1588     let result = try_opt!(rewrite_associated_type(
1589         ident,
1590         ty_opt,
1591         ty_param_bounds_opt,
1592         context,
1593         indent,
1594     ));
1595
1596     match defaultness {
1597         ast::Defaultness::Default => Some(format!("default {}", result)),
1598         _ => Some(result),
1599     }
1600 }
1601
1602 impl Rewrite for ast::FunctionRetTy {
1603     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1604         match *self {
1605             ast::FunctionRetTy::Default(_) => Some(String::new()),
1606             ast::FunctionRetTy::Ty(ref ty) => {
1607                 let inner_width = try_opt!(shape.width.checked_sub(3));
1608                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1609                     .map(|r| format!("-> {}", r))
1610             }
1611         }
1612     }
1613 }
1614
1615 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1616     match ty.node {
1617         ast::TyKind::Infer => {
1618             let original = context.snippet(ty.span);
1619             original != "_"
1620         }
1621         _ => false,
1622     }
1623 }
1624
1625 impl Rewrite for ast::Arg {
1626     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1627         if is_named_arg(self) {
1628             let mut result = try_opt!(
1629                 self.pat
1630                     .rewrite(context, Shape::legacy(shape.width, shape.indent))
1631             );
1632
1633             if !is_empty_infer(context, &*self.ty) {
1634                 if context.config.space_before_type_annotation() {
1635                     result.push_str(" ");
1636                 }
1637                 result.push_str(":");
1638                 if context.config.space_after_type_annotation_colon() {
1639                     result.push_str(" ");
1640                 }
1641                 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1642                 let ty_str = try_opt!(self.ty.rewrite(
1643                     context,
1644                     Shape::legacy(max_width, shape.indent + result.len()),
1645                 ));
1646                 result.push_str(&ty_str);
1647             }
1648
1649             Some(result)
1650         } else {
1651             self.ty.rewrite(context, shape)
1652         }
1653     }
1654 }
1655
1656 fn rewrite_explicit_self(
1657     explicit_self: &ast::ExplicitSelf,
1658     args: &[ast::Arg],
1659     context: &RewriteContext,
1660 ) -> Option<String> {
1661     match explicit_self.node {
1662         ast::SelfKind::Region(lt, m) => {
1663             let mut_str = format_mutability(m);
1664             match lt {
1665                 Some(ref l) => {
1666                     let lifetime_str = try_opt!(l.rewrite(
1667                         context,
1668                         Shape::legacy(context.config.max_width(), Indent::empty()),
1669                     ));
1670                     Some(format!("&{} {}self", lifetime_str, mut_str))
1671                 }
1672                 None => Some(format!("&{}self", mut_str)),
1673             }
1674         }
1675         ast::SelfKind::Explicit(ref ty, _) => {
1676             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1677
1678             let mutability = explicit_self_mutability(&args[0]);
1679             let type_str = try_opt!(ty.rewrite(
1680                 context,
1681                 Shape::legacy(context.config.max_width(), Indent::empty()),
1682             ));
1683
1684             Some(format!(
1685                 "{}self: {}",
1686                 format_mutability(mutability),
1687                 type_str
1688             ))
1689         }
1690         ast::SelfKind::Value(_) => {
1691             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1692
1693             let mutability = explicit_self_mutability(&args[0]);
1694
1695             Some(format!("{}self", format_mutability(mutability)))
1696         }
1697     }
1698 }
1699
1700 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1701 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1702 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1703     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1704         mutability
1705     } else {
1706         unreachable!()
1707     }
1708 }
1709
1710 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1711     if is_named_arg(arg) {
1712         arg.pat.span.lo()
1713     } else {
1714         arg.ty.span.lo()
1715     }
1716 }
1717
1718 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1719     match arg.ty.node {
1720         ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1721         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1722         _ => arg.ty.span.hi(),
1723     }
1724 }
1725
1726 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1727     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1728         ident.node != symbol::keywords::Invalid.ident()
1729     } else {
1730         true
1731     }
1732 }
1733
1734 // Return type is (result, force_new_line_for_brace)
1735 fn rewrite_fn_base(
1736     context: &RewriteContext,
1737     indent: Indent,
1738     ident: ast::Ident,
1739     fd: &ast::FnDecl,
1740     generics: &ast::Generics,
1741     unsafety: ast::Unsafety,
1742     constness: ast::Constness,
1743     defaultness: ast::Defaultness,
1744     abi: abi::Abi,
1745     vis: &ast::Visibility,
1746     span: Span,
1747     newline_brace: bool,
1748     has_body: bool,
1749     has_braces: bool,
1750 ) -> Option<(String, bool)> {
1751     let mut force_new_line_for_brace = false;
1752
1753     let where_clause = &generics.where_clause;
1754
1755     let mut result = String::with_capacity(1024);
1756     // Vis defaultness constness unsafety abi.
1757     result.push_str(&*format_visibility(vis));
1758     result.push_str(format_defaultness(defaultness));
1759     result.push_str(format_constness(constness));
1760     result.push_str(format_unsafety(unsafety));
1761     if abi != abi::Abi::Rust {
1762         result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1763     }
1764
1765     // fn foo
1766     result.push_str("fn ");
1767     result.push_str(&ident.to_string());
1768
1769     // Generics.
1770     let overhead = if has_braces && !newline_brace {
1771         // 4 = `() {`
1772         4
1773     } else {
1774         // 2 = `()`
1775         2
1776     };
1777     let used_width = last_line_used_width(&result, indent.width());
1778     let one_line_budget = context
1779         .config
1780         .max_width()
1781         .checked_sub(used_width + overhead)
1782         .unwrap_or(0);
1783     let shape = Shape {
1784         width: one_line_budget,
1785         indent: indent,
1786         offset: used_width,
1787     };
1788     let g_span = mk_sp(span.lo(), fd.output.span().lo());
1789     let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1790     result.push_str(&generics_str);
1791
1792     let snuggle_angle_bracket = generics_str
1793         .lines()
1794         .last()
1795         .map_or(false, |l| l.trim_left().len() == 1);
1796
1797     // Note that the width and indent don't really matter, we'll re-layout the
1798     // return type later anyway.
1799     let ret_str = try_opt!(
1800         fd.output
1801             .rewrite(context, Shape::indented(indent, context.config))
1802     );
1803
1804     let multi_line_ret_str = ret_str.contains('\n');
1805     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1806
1807     // Args.
1808     let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1809         context,
1810         &result,
1811         indent,
1812         ret_str_len,
1813         newline_brace,
1814         has_braces,
1815         multi_line_ret_str,
1816     ));
1817
1818     debug!(
1819         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1820         one_line_budget,
1821         multi_line_budget,
1822         arg_indent
1823     );
1824
1825     // Check if vertical layout was forced.
1826     if one_line_budget == 0 {
1827         if snuggle_angle_bracket {
1828             result.push('(');
1829         } else if context.config.fn_args_paren_newline() {
1830             result.push('\n');
1831             result.push_str(&arg_indent.to_string(context.config));
1832             if context.config.fn_args_layout() == IndentStyle::Visual {
1833                 arg_indent = arg_indent + 1; // extra space for `(`
1834             }
1835             result.push('(');
1836         } else {
1837             result.push_str("(");
1838             if context.config.fn_args_layout() == IndentStyle::Visual {
1839                 result.push('\n');
1840                 result.push_str(&arg_indent.to_string(context.config));
1841             }
1842         }
1843     } else {
1844         result.push('(');
1845     }
1846     if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1847         result.push(' ')
1848     }
1849
1850     // A conservative estimation, to goal is to be over all parens in generics
1851     let args_start = generics
1852         .ty_params
1853         .last()
1854         .map_or(span.lo(), |tp| end_typaram(tp));
1855     let args_end = if fd.inputs.is_empty() {
1856         context
1857             .codemap
1858             .span_after(mk_sp(args_start, span.hi()), ")")
1859     } else {
1860         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1861         context.codemap.span_after(last_span, ")")
1862     };
1863     let args_span = mk_sp(
1864         context
1865             .codemap
1866             .span_after(mk_sp(args_start, span.hi()), "("),
1867         args_end,
1868     );
1869     let arg_str = try_opt!(rewrite_args(
1870         context,
1871         &fd.inputs,
1872         fd.get_self().as_ref(),
1873         one_line_budget,
1874         multi_line_budget,
1875         indent,
1876         arg_indent,
1877         args_span,
1878         fd.variadic,
1879         generics_str.contains('\n'),
1880     ));
1881
1882     let put_args_in_block = match context.config.fn_args_layout() {
1883         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1884         _ => false,
1885     } && !fd.inputs.is_empty();
1886
1887     let mut args_last_line_contains_comment = false;
1888     if put_args_in_block {
1889         arg_indent = indent.block_indent(context.config);
1890         result.push('\n');
1891         result.push_str(&arg_indent.to_string(context.config));
1892         result.push_str(&arg_str);
1893         result.push('\n');
1894         result.push_str(&indent.to_string(context.config));
1895         result.push(')');
1896     } else {
1897         result.push_str(&arg_str);
1898         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1899         // Put the closing brace on the next line if it overflows the max width.
1900         // 1 = `)`
1901         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1902             result.push('\n');
1903         }
1904         if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1905             result.push(' ')
1906         }
1907         // If the last line of args contains comment, we cannot put the closing paren
1908         // on the same line.
1909         if arg_str
1910             .lines()
1911             .last()
1912             .map_or(false, |last_line| last_line.contains("//"))
1913         {
1914             args_last_line_contains_comment = true;
1915             result.push('\n');
1916             result.push_str(&arg_indent.to_string(context.config));
1917         }
1918         result.push(')');
1919     }
1920
1921     // Return type.
1922     if let ast::FunctionRetTy::Ty(..) = fd.output {
1923         let ret_should_indent = match context.config.fn_args_layout() {
1924             // If our args are block layout then we surely must have space.
1925             IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1926             _ if args_last_line_contains_comment => false,
1927             _ if result.contains('\n') || multi_line_ret_str => true,
1928             _ => {
1929                 // If the return type would push over the max width, then put the return type on
1930                 // a new line. With the +1 for the signature length an additional space between
1931                 // the closing parenthesis of the argument and the arrow '->' is considered.
1932                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1933
1934                 // If there is no where clause, take into account the space after the return type
1935                 // and the brace.
1936                 if where_clause.predicates.is_empty() {
1937                     sig_length += 2;
1938                 }
1939
1940                 sig_length > context.config.max_width()
1941             }
1942         };
1943         let ret_indent = if ret_should_indent {
1944             let indent = match context.config.fn_return_indent() {
1945                 ReturnIndent::WithWhereClause => indent + 4,
1946                 // Aligning with non-existent args looks silly.
1947                 _ if arg_str.is_empty() => {
1948                     force_new_line_for_brace = true;
1949                     indent + 4
1950                 }
1951                 // FIXME: we might want to check that using the arg indent
1952                 // doesn't blow our budget, and if it does, then fallback to
1953                 // the where clause indent.
1954                 _ => arg_indent,
1955             };
1956
1957             result.push('\n');
1958             result.push_str(&indent.to_string(context.config));
1959             indent
1960         } else {
1961             result.push(' ');
1962             Indent::new(indent.block_indent, last_line_width(&result))
1963         };
1964
1965         if multi_line_ret_str || ret_should_indent {
1966             // Now that we know the proper indent and width, we need to
1967             // re-layout the return type.
1968             let ret_str = try_opt!(
1969                 fd.output
1970                     .rewrite(context, Shape::indented(ret_indent, context.config))
1971             );
1972             result.push_str(&ret_str);
1973         } else {
1974             result.push_str(&ret_str);
1975         }
1976
1977         // Comment between return type and the end of the decl.
1978         let snippet_lo = fd.output.span().hi();
1979         if where_clause.predicates.is_empty() {
1980             let snippet_hi = span.hi();
1981             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1982             // Try to preserve the layout of the original snippet.
1983             let original_starts_with_newline = snippet
1984                 .find(|c| c != ' ')
1985                 .map_or(false, |i| snippet[i..].starts_with('\n'));
1986             let original_ends_with_newline = snippet
1987                 .rfind(|c| c != ' ')
1988                 .map_or(false, |i| snippet[i..].ends_with('\n'));
1989             let snippet = snippet.trim();
1990             if !snippet.is_empty() {
1991                 result.push(if original_starts_with_newline {
1992                     '\n'
1993                 } else {
1994                     ' '
1995                 });
1996                 result.push_str(snippet);
1997                 if original_ends_with_newline {
1998                     force_new_line_for_brace = true;
1999                 }
2000             }
2001         }
2002     }
2003
2004     let should_compress_where = match context.config.where_density() {
2005         Density::Compressed => !result.contains('\n'),
2006         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2007         _ => false,
2008     };
2009
2010     let pos_before_where = match fd.output {
2011         ast::FunctionRetTy::Default(..) => args_span.hi(),
2012         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2013     };
2014
2015     if where_clause.predicates.len() == 1 && should_compress_where {
2016         let budget = context
2017             .config
2018             .max_width()
2019             .checked_sub(last_line_used_width(&result, indent.width()))
2020             .unwrap_or(0);
2021         if let Some(where_clause_str) = rewrite_where_clause(
2022             context,
2023             where_clause,
2024             context.config.fn_brace_style(),
2025             Shape::legacy(budget, indent),
2026             Density::Compressed,
2027             "{",
2028             Some(span.hi()),
2029             pos_before_where,
2030             WhereClauseOption::compressed(),
2031         ) {
2032             result.push_str(&where_clause_str);
2033             force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2034             return Some((result, force_new_line_for_brace));
2035         }
2036     }
2037
2038     let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2039     let where_clause_str = try_opt!(rewrite_where_clause(
2040         context,
2041         where_clause,
2042         context.config.fn_brace_style(),
2043         Shape::indented(indent, context.config),
2044         Density::Tall,
2045         "{",
2046         Some(span.hi()),
2047         pos_before_where,
2048         option,
2049     ));
2050     // If there are neither where clause nor return type, we may be missing comments between
2051     // args and `{`.
2052     if where_clause_str.is_empty() {
2053         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2054             match recover_missing_comment_in_span(
2055                 mk_sp(args_span.hi(), ret_span.hi()),
2056                 shape,
2057                 context,
2058                 last_line_width(&result),
2059             ) {
2060                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2061                     result.push_str(missing_comment);
2062                     force_new_line_for_brace = true;
2063                 }
2064                 _ => (),
2065             }
2066         }
2067     }
2068
2069     result.push_str(&where_clause_str);
2070
2071     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2072     Some((result, force_new_line_for_brace))
2073 }
2074
2075 #[derive(Copy, Clone)]
2076 struct WhereClauseOption {
2077     suppress_comma: bool, // Force no trailing comma
2078     snuggle: bool,        // Do not insert newline before `where`
2079     compress_where: bool, // Try single line where clause instead of vertical layout
2080 }
2081
2082 impl WhereClauseOption {
2083     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2084         WhereClauseOption {
2085             suppress_comma: suppress_comma,
2086             snuggle: snuggle,
2087             compress_where: false,
2088         }
2089     }
2090
2091     pub fn compressed() -> WhereClauseOption {
2092         WhereClauseOption {
2093             suppress_comma: true,
2094             snuggle: false,
2095             compress_where: true,
2096         }
2097     }
2098
2099     pub fn snuggled(current: &str) -> WhereClauseOption {
2100         WhereClauseOption {
2101             suppress_comma: false,
2102             snuggle: trimmed_last_line_width(current) == 1,
2103             compress_where: false,
2104         }
2105     }
2106 }
2107
2108 fn rewrite_args(
2109     context: &RewriteContext,
2110     args: &[ast::Arg],
2111     explicit_self: Option<&ast::ExplicitSelf>,
2112     one_line_budget: usize,
2113     multi_line_budget: usize,
2114     indent: Indent,
2115     arg_indent: Indent,
2116     span: Span,
2117     variadic: bool,
2118     generics_str_contains_newline: bool,
2119 ) -> Option<String> {
2120     let mut arg_item_strs = try_opt!(
2121         args.iter()
2122             .map(|arg| {
2123                 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2124             })
2125             .collect::<Option<Vec<_>>>()
2126     );
2127
2128     // Account for sugary self.
2129     // FIXME: the comment for the self argument is dropped. This is blocked
2130     // on rust issue #27522.
2131     let min_args = explicit_self
2132         .and_then(|explicit_self| {
2133             rewrite_explicit_self(explicit_self, args, context)
2134         })
2135         .map_or(1, |self_str| {
2136             arg_item_strs[0] = self_str;
2137             2
2138         });
2139
2140     // Comments between args.
2141     let mut arg_items = Vec::new();
2142     if min_args == 2 {
2143         arg_items.push(ListItem::from_str(""));
2144     }
2145
2146     // FIXME(#21): if there are no args, there might still be a comment, but
2147     // without spans for the comment or parens, there is no chance of
2148     // getting it right. You also don't get to put a comment on self, unless
2149     // it is explicit.
2150     if args.len() >= min_args || variadic {
2151         let comment_span_start = if min_args == 2 {
2152             let second_arg_start = if arg_has_pattern(&args[1]) {
2153                 args[1].pat.span.lo()
2154             } else {
2155                 args[1].ty.span.lo()
2156             };
2157             let reduced_span = mk_sp(span.lo(), second_arg_start);
2158
2159             context.codemap.span_after_last(reduced_span, ",")
2160         } else {
2161             span.lo()
2162         };
2163
2164         enum ArgumentKind<'a> {
2165             Regular(&'a ast::Arg),
2166             Variadic(BytePos),
2167         }
2168
2169         let variadic_arg = if variadic {
2170             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2171             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2172             Some(ArgumentKind::Variadic(variadic_start))
2173         } else {
2174             None
2175         };
2176
2177         let more_items = itemize_list(
2178             context.codemap,
2179             args[min_args - 1..]
2180                 .iter()
2181                 .map(ArgumentKind::Regular)
2182                 .chain(variadic_arg),
2183             ")",
2184             |arg| match *arg {
2185                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2186                 ArgumentKind::Variadic(start) => start,
2187             },
2188             |arg| match *arg {
2189                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2190                 ArgumentKind::Variadic(start) => start + BytePos(3),
2191             },
2192             |arg| match *arg {
2193                 ArgumentKind::Regular(..) => None,
2194                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2195             },
2196             comment_span_start,
2197             span.hi(),
2198             false,
2199         );
2200
2201         arg_items.extend(more_items);
2202     }
2203
2204     let fits_in_one_line = !generics_str_contains_newline &&
2205         (arg_items.is_empty() || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2206
2207     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2208         item.item = Some(arg);
2209     }
2210
2211     let last_line_ends_with_comment = arg_items
2212         .iter()
2213         .last()
2214         .and_then(|item| item.post_comment.as_ref())
2215         .map_or(false, |s| s.trim().starts_with("//"));
2216
2217     let (indent, trailing_comma) = match context.config.fn_args_layout() {
2218         IndentStyle::Block if fits_in_one_line => {
2219             (indent.block_indent(context.config), SeparatorTactic::Never)
2220         }
2221         IndentStyle::Block => (
2222             indent.block_indent(context.config),
2223             context.config.trailing_comma(),
2224         ),
2225         IndentStyle::Visual if last_line_ends_with_comment => {
2226             (arg_indent, context.config.trailing_comma())
2227         }
2228         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2229     };
2230
2231     let tactic = definitive_tactic(
2232         &arg_items,
2233         context.config.fn_args_density().to_list_tactic(),
2234         Separator::Comma,
2235         one_line_budget,
2236     );
2237     let budget = match tactic {
2238         DefinitiveListTactic::Horizontal => one_line_budget,
2239         _ => multi_line_budget,
2240     };
2241
2242     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2243
2244     let fmt = ListFormatting {
2245         tactic: tactic,
2246         separator: ",",
2247         trailing_separator: if variadic {
2248             SeparatorTactic::Never
2249         } else {
2250             trailing_comma
2251         },
2252         separator_place: SeparatorPlace::Back,
2253         shape: Shape::legacy(budget, indent),
2254         ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2255         preserve_newline: true,
2256         config: context.config,
2257     };
2258
2259     write_list(&arg_items, &fmt)
2260 }
2261
2262 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2263     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2264         ident.node != symbol::keywords::Invalid.ident()
2265     } else {
2266         true
2267     }
2268 }
2269
2270 fn compute_budgets_for_args(
2271     context: &RewriteContext,
2272     result: &str,
2273     indent: Indent,
2274     ret_str_len: usize,
2275     newline_brace: bool,
2276     has_braces: bool,
2277     force_vertical_layout: bool,
2278 ) -> Option<((usize, usize, Indent))> {
2279     debug!(
2280         "compute_budgets_for_args {} {:?}, {}, {}",
2281         result.len(),
2282         indent,
2283         ret_str_len,
2284         newline_brace
2285     );
2286     // Try keeping everything on the same line.
2287     if !result.contains('\n') && !force_vertical_layout {
2288         // 2 = `()`, 3 = `() `, space is before ret_string.
2289         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2290         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2291         if has_braces {
2292             if !newline_brace {
2293                 // 2 = `{}`
2294                 used_space += 2;
2295             }
2296         } else {
2297             // 1 = `;`
2298             used_space += 1;
2299         }
2300         let one_line_budget = context
2301             .config
2302             .max_width()
2303             .checked_sub(used_space)
2304             .unwrap_or(0);
2305
2306         if one_line_budget > 0 {
2307             // 4 = "() {".len()
2308             let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2309                 IndentStyle::Block => {
2310                     let indent = indent.block_indent(context.config);
2311                     let budget =
2312                         try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2313                     (indent, budget)
2314                 }
2315                 IndentStyle::Visual => {
2316                     let indent = indent + result.len() + 1;
2317                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2318                     let budget =
2319                         try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2320                     (indent, budget)
2321                 }
2322             };
2323
2324             return Some((one_line_budget, multi_line_budget, indent));
2325         }
2326     }
2327
2328     // Didn't work. we must force vertical layout and put args on a newline.
2329     let new_indent = indent.block_indent(context.config);
2330     let used_space = match context.config.fn_args_layout() {
2331         // 1 = `,`
2332         IndentStyle::Block => new_indent.width() + 1,
2333         // Account for `)` and possibly ` {`.
2334         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2335     };
2336     let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2337     Some((0, max_space, new_indent))
2338 }
2339
2340 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2341     match (config.fn_brace_style(), config.where_density()) {
2342         (BraceStyle::AlwaysNextLine, _) => true,
2343         (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2344         (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2345         (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2346         _ => false,
2347     }
2348 }
2349
2350 fn rewrite_generics(
2351     context: &RewriteContext,
2352     generics: &ast::Generics,
2353     shape: Shape,
2354     span: Span,
2355 ) -> Option<String> {
2356     let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2357     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2358     rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2359         rewrite_generics_inner(context, generics, g_shape, 0, span)
2360     })
2361 }
2362
2363 fn rewrite_generics_inner(
2364     context: &RewriteContext,
2365     generics: &ast::Generics,
2366     shape: Shape,
2367     one_line_width: usize,
2368     span: Span,
2369 ) -> Option<String> {
2370     // FIXME: convert bounds to where clauses where they get too big or if
2371     // there is a where clause at all.
2372     let lifetimes: &[_] = &generics.lifetimes;
2373     let tys: &[_] = &generics.ty_params;
2374     if lifetimes.is_empty() && tys.is_empty() {
2375         return Some(String::new());
2376     }
2377
2378     // Strings for the generics.
2379     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2380     let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2381
2382     // Extract comments between generics.
2383     let lt_spans = lifetimes.iter().map(|l| {
2384         let hi = if l.bounds.is_empty() {
2385             l.lifetime.span.hi()
2386         } else {
2387             l.bounds[l.bounds.len() - 1].span.hi()
2388         };
2389         mk_sp(l.lifetime.span.lo(), hi)
2390     });
2391     let ty_spans = tys.iter().map(|ty| ty.span());
2392
2393     let items = itemize_list(
2394         context.codemap,
2395         lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2396         ">",
2397         |&(sp, _)| sp.lo(),
2398         |&(sp, _)| sp.hi(),
2399         // FIXME: don't clone
2400         |&(_, ref str)| str.clone(),
2401         context.codemap.span_after(span, "<"),
2402         span.hi(),
2403         false,
2404     );
2405     format_generics_item_list(context, items, shape, one_line_width)
2406 }
2407
2408 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2409     match config.generics_indent() {
2410         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2411         IndentStyle::Block => {
2412             // 1 = ","
2413             shape
2414                 .block()
2415                 .block_indent(config.tab_spaces())
2416                 .with_max_width(config)
2417                 .sub_width(1)
2418         }
2419     }
2420 }
2421
2422 pub fn format_generics_item_list<I>(
2423     context: &RewriteContext,
2424     items: I,
2425     shape: Shape,
2426     one_line_budget: usize,
2427 ) -> Option<String>
2428 where
2429     I: Iterator<Item = ListItem>,
2430 {
2431     let item_vec = items.collect::<Vec<_>>();
2432
2433     let tactic = definitive_tactic(
2434         &item_vec,
2435         ListTactic::HorizontalVertical,
2436         Separator::Comma,
2437         one_line_budget,
2438     );
2439     let fmt = ListFormatting {
2440         tactic: tactic,
2441         separator: ",",
2442         trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2443             SeparatorTactic::Never
2444         } else {
2445             context.config.trailing_comma()
2446         },
2447         separator_place: SeparatorPlace::Back,
2448         shape: shape,
2449         ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2450         preserve_newline: true,
2451         config: context.config,
2452     };
2453
2454     let list_str = try_opt!(write_list(&item_vec, &fmt));
2455
2456     Some(wrap_generics_with_angle_brackets(
2457         context,
2458         &list_str,
2459         shape.indent,
2460     ))
2461 }
2462
2463 pub fn wrap_generics_with_angle_brackets(
2464     context: &RewriteContext,
2465     list_str: &str,
2466     list_offset: Indent,
2467 ) -> String {
2468     if context.config.generics_indent() == IndentStyle::Block &&
2469         (list_str.contains('\n') || list_str.ends_with(','))
2470     {
2471         format!(
2472             "<\n{}{}\n{}>",
2473             list_offset.to_string(context.config),
2474             list_str,
2475             list_offset
2476                 .block_unindent(context.config)
2477                 .to_string(context.config)
2478         )
2479     } else if context.config.spaces_within_angle_brackets() {
2480         format!("< {} >", list_str)
2481     } else {
2482         format!("<{}>", list_str)
2483     }
2484 }
2485
2486 fn rewrite_trait_bounds(
2487     context: &RewriteContext,
2488     type_param_bounds: &ast::TyParamBounds,
2489     shape: Shape,
2490 ) -> Option<String> {
2491     let bounds: &[_] = type_param_bounds;
2492
2493     if bounds.is_empty() {
2494         return Some(String::new());
2495     }
2496     let bound_str = try_opt!(
2497         bounds
2498             .iter()
2499             .map(|ty_bound| ty_bound.rewrite(context, shape))
2500             .collect::<Option<Vec<_>>>()
2501     );
2502     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2503 }
2504
2505 fn rewrite_where_clause_rfc_style(
2506     context: &RewriteContext,
2507     where_clause: &ast::WhereClause,
2508     shape: Shape,
2509     terminator: &str,
2510     span_end: Option<BytePos>,
2511     span_end_before_where: BytePos,
2512     where_clause_option: WhereClauseOption,
2513 ) -> Option<String> {
2514     let block_shape = shape.block().with_max_width(context.config);
2515
2516     let (span_before, span_after) =
2517         missing_span_before_after_where(span_end_before_where, where_clause);
2518     let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2519         context,
2520         span_before,
2521         span_after,
2522         shape,
2523     ));
2524
2525     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2526         " ".to_owned()
2527     } else {
2528         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2529     };
2530
2531     let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2532     // each clause on one line, trailing comma (except if suppress_comma)
2533     let span_start = where_clause.predicates[0].span().lo();
2534     // If we don't have the start of the next span, then use the end of the
2535     // predicates, but that means we miss comments.
2536     let len = where_clause.predicates.len();
2537     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2538     let span_end = span_end.unwrap_or(end_of_preds);
2539     let items = itemize_list(
2540         context.codemap,
2541         where_clause.predicates.iter(),
2542         terminator,
2543         |pred| pred.span().lo(),
2544         |pred| pred.span().hi(),
2545         |pred| pred.rewrite(context, block_shape),
2546         span_start,
2547         span_end,
2548         false,
2549     );
2550     let comma_tactic = if where_clause_option.suppress_comma {
2551         SeparatorTactic::Never
2552     } else {
2553         context.config.trailing_comma()
2554     };
2555
2556     let fmt = ListFormatting {
2557         tactic: DefinitiveListTactic::Vertical,
2558         separator: ",",
2559         trailing_separator: comma_tactic,
2560         separator_place: SeparatorPlace::Back,
2561         shape: clause_shape,
2562         ends_with_newline: true,
2563         preserve_newline: true,
2564         config: context.config,
2565     };
2566     let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2567
2568     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2569         String::new()
2570     } else {
2571         format!("\n{}", shape.indent.to_string(context.config))
2572     };
2573     let newline_before_where = comment_separator(&comment_before, shape);
2574     let newline_after_where = comment_separator(&comment_after, clause_shape);
2575
2576     // 6 = `where `
2577     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2578         comment_after.is_empty() && !preds_str.contains('\n') &&
2579         6 + preds_str.len() <= shape.width
2580     {
2581         String::from(" ")
2582     } else {
2583         format!("\n{}", clause_shape.indent.to_string(context.config))
2584     };
2585     Some(format!(
2586         "{}{}{}where{}{}{}{}",
2587         starting_newline,
2588         comment_before,
2589         newline_before_where,
2590         newline_after_where,
2591         comment_after,
2592         clause_sep,
2593         preds_str
2594     ))
2595 }
2596
2597 fn rewrite_where_clause(
2598     context: &RewriteContext,
2599     where_clause: &ast::WhereClause,
2600     brace_style: BraceStyle,
2601     shape: Shape,
2602     density: Density,
2603     terminator: &str,
2604     span_end: Option<BytePos>,
2605     span_end_before_where: BytePos,
2606     where_clause_option: WhereClauseOption,
2607 ) -> Option<String> {
2608     if where_clause.predicates.is_empty() {
2609         return Some(String::new());
2610     }
2611
2612     if context.config.where_style() == Style::Rfc {
2613         return rewrite_where_clause_rfc_style(
2614             context,
2615             where_clause,
2616             shape,
2617             terminator,
2618             span_end,
2619             span_end_before_where,
2620             where_clause_option,
2621         );
2622     }
2623
2624     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2625
2626     let offset = match context.config.where_pred_indent() {
2627         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2628         // 6 = "where ".len()
2629         IndentStyle::Visual => shape.indent + extra_indent + 6,
2630     };
2631     // FIXME: if where_pred_indent != Visual, then the budgets below might
2632     // be out by a char or two.
2633
2634     let budget = context.config.max_width() - offset.width();
2635     let span_start = where_clause.predicates[0].span().lo();
2636     // If we don't have the start of the next span, then use the end of the
2637     // predicates, but that means we miss comments.
2638     let len = where_clause.predicates.len();
2639     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2640     let span_end = span_end.unwrap_or(end_of_preds);
2641     let items = itemize_list(
2642         context.codemap,
2643         where_clause.predicates.iter(),
2644         terminator,
2645         |pred| pred.span().lo(),
2646         |pred| pred.span().hi(),
2647         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2648         span_start,
2649         span_end,
2650         false,
2651     );
2652     let item_vec = items.collect::<Vec<_>>();
2653     // FIXME: we don't need to collect here if the where_layout isn't
2654     // HorizontalVertical.
2655     let tactic = definitive_tactic(
2656         &item_vec,
2657         context.config.where_layout(),
2658         Separator::Comma,
2659         budget,
2660     );
2661
2662     let mut comma_tactic = context.config.trailing_comma();
2663     // Kind of a hack because we don't usually have trailing commas in where clauses.
2664     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2665         comma_tactic = SeparatorTactic::Never;
2666     }
2667
2668     let fmt = ListFormatting {
2669         tactic: tactic,
2670         separator: ",",
2671         trailing_separator: comma_tactic,
2672         separator_place: SeparatorPlace::Back,
2673         shape: Shape::legacy(budget, offset),
2674         ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2675         preserve_newline: true,
2676         config: context.config,
2677     };
2678     let preds_str = try_opt!(write_list(&item_vec, &fmt));
2679
2680     let end_length = if terminator == "{" {
2681         // If the brace is on the next line we don't need to count it otherwise it needs two
2682         // characters " {"
2683         match brace_style {
2684             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2685             BraceStyle::PreferSameLine => 2,
2686         }
2687     } else if terminator == "=" {
2688         2
2689     } else {
2690         terminator.len()
2691     };
2692     if density == Density::Tall || preds_str.contains('\n') ||
2693         shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2694     {
2695         Some(format!(
2696             "\n{}where {}",
2697             (shape.indent + extra_indent).to_string(context.config),
2698             preds_str
2699         ))
2700     } else {
2701         Some(format!(" where {}", preds_str))
2702     }
2703 }
2704
2705 fn missing_span_before_after_where(
2706     before_item_span_end: BytePos,
2707     where_clause: &ast::WhereClause,
2708 ) -> (Span, Span) {
2709     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2710     // 5 = `where`
2711     let pos_after_where = where_clause.span.lo() + BytePos(5);
2712     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2713     (missing_span_before, missing_span_after)
2714 }
2715
2716 fn rewrite_comments_before_after_where(
2717     context: &RewriteContext,
2718     span_before_where: Span,
2719     span_after_where: Span,
2720     shape: Shape,
2721 ) -> Option<(String, String)> {
2722     let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2723     let after_comment = try_opt!(rewrite_missing_comment(
2724         span_after_where,
2725         shape.block_indent(context.config.tab_spaces()),
2726         context,
2727     ));
2728     Some((before_comment, after_comment))
2729 }
2730
2731 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2732     format!("{}{}{}", format_visibility(vis), item_name, ident)
2733 }
2734
2735 fn format_generics(
2736     context: &RewriteContext,
2737     generics: &ast::Generics,
2738     opener: &str,
2739     terminator: &str,
2740     brace_style: BraceStyle,
2741     force_same_line_brace: bool,
2742     offset: Indent,
2743     span: Span,
2744     used_width: usize,
2745 ) -> Option<String> {
2746     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2747     let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2748
2749     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2750         let budget = context
2751             .config
2752             .max_width()
2753             .checked_sub(last_line_used_width(&result, offset.width()))
2754             .unwrap_or(0);
2755         let option = WhereClauseOption::snuggled(&result);
2756         let where_clause_str = try_opt!(rewrite_where_clause(
2757             context,
2758             &generics.where_clause,
2759             brace_style,
2760             Shape::legacy(budget, offset.block_only()),
2761             Density::Tall,
2762             terminator,
2763             Some(span.hi()),
2764             generics.span.hi(),
2765             option,
2766         ));
2767         result.push_str(&where_clause_str);
2768         force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2769             (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2770     } else {
2771         force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2772             brace_style != BraceStyle::AlwaysNextLine
2773     };
2774     let total_used_width = last_line_used_width(&result, used_width);
2775     let remaining_budget = context
2776         .config
2777         .max_width()
2778         .checked_sub(total_used_width)
2779         .unwrap_or(0);
2780     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2781     // and hence we take the closer into account as well for one line budget.
2782     // We assume that the closer has the same length as the opener.
2783     let overhead = if force_same_line_brace {
2784         1 + opener.len() + opener.len()
2785     } else {
2786         1 + opener.len()
2787     };
2788     let forbid_same_line_brace = overhead > remaining_budget;
2789     if !forbid_same_line_brace && same_line_brace {
2790         result.push(' ');
2791     } else {
2792         result.push('\n');
2793         result.push_str(&offset.block_only().to_string(context.config));
2794     }
2795     result.push_str(opener);
2796
2797     Some(result)
2798 }
2799
2800 impl Rewrite for ast::ForeignItem {
2801     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2802         let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2803         // Drop semicolon or it will be interpreted as comment.
2804         // FIXME: this may be a faulty span from libsyntax.
2805         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2806
2807         let item_str = try_opt!(match self.node {
2808             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2809                 rewrite_fn_base(
2810                     context,
2811                     shape.indent,
2812                     self.ident,
2813                     fn_decl,
2814                     generics,
2815                     ast::Unsafety::Normal,
2816                     ast::Constness::NotConst,
2817                     ast::Defaultness::Final,
2818                     // These are not actually rust functions,
2819                     // but we format them as such.
2820                     abi::Abi::Rust,
2821                     &self.vis,
2822                     span,
2823                     false,
2824                     false,
2825                     false,
2826                 ).map(|(s, _)| format!("{};", s))
2827             }
2828             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2829                 // FIXME(#21): we're dropping potential comments in between the
2830                 // function keywords here.
2831                 let vis = format_visibility(&self.vis);
2832                 let mut_str = if is_mutable { "mut " } else { "" };
2833                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2834                 // 1 = ;
2835                 let shape = try_opt!(shape.sub_width(1));
2836                 ty.rewrite(context, shape).map(|ty_str| {
2837                     // 1 = space between prefix and type.
2838                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2839                         String::from(" ")
2840                     } else {
2841                         let nested_indent = shape.indent.block_indent(context.config);
2842                         format!("\n{}", nested_indent.to_string(context.config))
2843                     };
2844                     format!("{}{}{};", prefix, sep, ty_str)
2845                 })
2846             }
2847         });
2848
2849         let missing_span = if self.attrs.is_empty() {
2850             mk_sp(self.span.lo(), self.span.lo())
2851         } else {
2852             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2853         };
2854         combine_strs_with_missing_comments(
2855             context,
2856             &attrs_str,
2857             &item_str,
2858             missing_span,
2859             shape,
2860             false,
2861         )
2862     }
2863 }