]> git.lizzy.rs Git - rust.git/blob - src/items.rs
67d547498286b3e61048b8ca9281c8950321fcc0
[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(ref 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(ref 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.len() > 0 {
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 {
1830             if context.config.fn_args_paren_newline() {
1831                 result.push('\n');
1832                 result.push_str(&arg_indent.to_string(context.config));
1833                 if context.config.fn_args_layout() == IndentStyle::Visual {
1834                     arg_indent = arg_indent + 1; // extra space for `(`
1835                 }
1836                 result.push('(');
1837             } else {
1838                 result.push_str("(");
1839                 if context.config.fn_args_layout() == IndentStyle::Visual {
1840                     result.push('\n');
1841                     result.push_str(&arg_indent.to_string(context.config));
1842                 }
1843             }
1844         }
1845     } else {
1846         result.push('(');
1847     }
1848     if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1849         result.push(' ')
1850     }
1851
1852     // A conservative estimation, to goal is to be over all parens in generics
1853     let args_start = generics
1854         .ty_params
1855         .last()
1856         .map_or(span.lo(), |tp| end_typaram(tp));
1857     let args_end = if fd.inputs.is_empty() {
1858         context
1859             .codemap
1860             .span_after(mk_sp(args_start, span.hi()), ")")
1861     } else {
1862         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1863         context.codemap.span_after(last_span, ")")
1864     };
1865     let args_span = mk_sp(
1866         context
1867             .codemap
1868             .span_after(mk_sp(args_start, span.hi()), "("),
1869         args_end,
1870     );
1871     let arg_str = try_opt!(rewrite_args(
1872         context,
1873         &fd.inputs,
1874         fd.get_self().as_ref(),
1875         one_line_budget,
1876         multi_line_budget,
1877         indent,
1878         arg_indent,
1879         args_span,
1880         fd.variadic,
1881         generics_str.contains('\n'),
1882     ));
1883
1884     let put_args_in_block = match context.config.fn_args_layout() {
1885         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1886         _ => false,
1887     } && !fd.inputs.is_empty();
1888
1889     let mut args_last_line_contains_comment = false;
1890     if put_args_in_block {
1891         arg_indent = indent.block_indent(context.config);
1892         result.push('\n');
1893         result.push_str(&arg_indent.to_string(context.config));
1894         result.push_str(&arg_str);
1895         result.push('\n');
1896         result.push_str(&indent.to_string(context.config));
1897         result.push(')');
1898     } else {
1899         result.push_str(&arg_str);
1900         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1901         // Put the closing brace on the next line if it overflows the max width.
1902         // 1 = `)`
1903         if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1904             result.push('\n');
1905         }
1906         if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1907             result.push(' ')
1908         }
1909         // If the last line of args contains comment, we cannot put the closing paren
1910         // on the same line.
1911         if arg_str
1912             .lines()
1913             .last()
1914             .map_or(false, |last_line| last_line.contains("//"))
1915         {
1916             args_last_line_contains_comment = true;
1917             result.push('\n');
1918             result.push_str(&arg_indent.to_string(context.config));
1919         }
1920         result.push(')');
1921     }
1922
1923     // Return type.
1924     if let ast::FunctionRetTy::Ty(..) = fd.output {
1925         let ret_should_indent = match context.config.fn_args_layout() {
1926             // If our args are block layout then we surely must have space.
1927             IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1928             _ if args_last_line_contains_comment => false,
1929             _ if result.contains('\n') || multi_line_ret_str => true,
1930             _ => {
1931                 // If the return type would push over the max width, then put the return type on
1932                 // a new line. With the +1 for the signature length an additional space between
1933                 // the closing parenthesis of the argument and the arrow '->' is considered.
1934                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1935
1936                 // If there is no where clause, take into account the space after the return type
1937                 // and the brace.
1938                 if where_clause.predicates.is_empty() {
1939                     sig_length += 2;
1940                 }
1941
1942                 sig_length > context.config.max_width()
1943             }
1944         };
1945         let ret_indent = if ret_should_indent {
1946             let indent = match context.config.fn_return_indent() {
1947                 ReturnIndent::WithWhereClause => indent + 4,
1948                 // Aligning with non-existent args looks silly.
1949                 _ if arg_str.is_empty() => {
1950                     force_new_line_for_brace = true;
1951                     indent + 4
1952                 }
1953                 // FIXME: we might want to check that using the arg indent
1954                 // doesn't blow our budget, and if it does, then fallback to
1955                 // the where clause indent.
1956                 _ => arg_indent,
1957             };
1958
1959             result.push('\n');
1960             result.push_str(&indent.to_string(context.config));
1961             indent
1962         } else {
1963             result.push(' ');
1964             Indent::new(indent.block_indent, last_line_width(&result))
1965         };
1966
1967         if multi_line_ret_str || ret_should_indent {
1968             // Now that we know the proper indent and width, we need to
1969             // re-layout the return type.
1970             let ret_str = try_opt!(
1971                 fd.output
1972                     .rewrite(context, Shape::indented(ret_indent, context.config))
1973             );
1974             result.push_str(&ret_str);
1975         } else {
1976             result.push_str(&ret_str);
1977         }
1978
1979         // Comment between return type and the end of the decl.
1980         let snippet_lo = fd.output.span().hi();
1981         if where_clause.predicates.is_empty() {
1982             let snippet_hi = span.hi();
1983             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1984             // Try to preserve the layout of the original snippet.
1985             let original_starts_with_newline = snippet
1986                 .find(|c| c != ' ')
1987                 .map_or(false, |i| snippet[i..].starts_with('\n'));
1988             let original_ends_with_newline = snippet
1989                 .rfind(|c| c != ' ')
1990                 .map_or(false, |i| snippet[i..].ends_with('\n'));
1991             let snippet = snippet.trim();
1992             if !snippet.is_empty() {
1993                 result.push(if original_starts_with_newline {
1994                     '\n'
1995                 } else {
1996                     ' '
1997                 });
1998                 result.push_str(snippet);
1999                 if original_ends_with_newline {
2000                     force_new_line_for_brace = true;
2001                 }
2002             }
2003         }
2004     }
2005
2006     let should_compress_where = match context.config.where_density() {
2007         Density::Compressed => !result.contains('\n'),
2008         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2009         _ => false,
2010     };
2011
2012     let pos_before_where = match fd.output {
2013         ast::FunctionRetTy::Default(..) => args_span.hi(),
2014         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2015     };
2016
2017     if where_clause.predicates.len() == 1 && should_compress_where {
2018         let budget = context
2019             .config
2020             .max_width()
2021             .checked_sub(last_line_used_width(&result, indent.width()))
2022             .unwrap_or(0);
2023         if let Some(where_clause_str) = rewrite_where_clause(
2024             context,
2025             where_clause,
2026             context.config.fn_brace_style(),
2027             Shape::legacy(budget, indent),
2028             Density::Compressed,
2029             "{",
2030             Some(span.hi()),
2031             pos_before_where,
2032             WhereClauseOption::compressed(),
2033         ) {
2034             result.push_str(&where_clause_str);
2035             force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2036             return Some((result, force_new_line_for_brace));
2037         }
2038     }
2039
2040     let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2041     let where_clause_str = try_opt!(rewrite_where_clause(
2042         context,
2043         where_clause,
2044         context.config.fn_brace_style(),
2045         Shape::indented(indent, context.config),
2046         Density::Tall,
2047         "{",
2048         Some(span.hi()),
2049         pos_before_where,
2050         option,
2051     ));
2052     // If there are neither where clause nor return type, we may be missing comments between
2053     // args and `{`.
2054     if where_clause_str.is_empty() {
2055         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2056             match recover_missing_comment_in_span(
2057                 mk_sp(args_span.hi(), ret_span.hi()),
2058                 shape,
2059                 context,
2060                 last_line_width(&result),
2061             ) {
2062                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2063                     result.push_str(missing_comment);
2064                     force_new_line_for_brace = true;
2065                 }
2066                 _ => (),
2067             }
2068         }
2069     }
2070
2071     result.push_str(&where_clause_str);
2072
2073     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2074     return Some((result, force_new_line_for_brace));
2075 }
2076
2077 struct WhereClauseOption {
2078     suppress_comma: bool, // Force no trailing comma
2079     snuggle: bool,        // Do not insert newline before `where`
2080     compress_where: bool, // Try single line where clause instead of vertical layout
2081 }
2082
2083 impl WhereClauseOption {
2084     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2085         WhereClauseOption {
2086             suppress_comma: suppress_comma,
2087             snuggle: snuggle,
2088             compress_where: false,
2089         }
2090     }
2091
2092     pub fn compressed() -> WhereClauseOption {
2093         WhereClauseOption {
2094             suppress_comma: true,
2095             snuggle: false,
2096             compress_where: true,
2097         }
2098     }
2099
2100     pub fn snuggled(current: &str) -> WhereClauseOption {
2101         WhereClauseOption {
2102             suppress_comma: false,
2103             snuggle: trimmed_last_line_width(current) == 1,
2104             compress_where: false,
2105         }
2106     }
2107 }
2108
2109 fn rewrite_args(
2110     context: &RewriteContext,
2111     args: &[ast::Arg],
2112     explicit_self: Option<&ast::ExplicitSelf>,
2113     one_line_budget: usize,
2114     multi_line_budget: usize,
2115     indent: Indent,
2116     arg_indent: Indent,
2117     span: Span,
2118     variadic: bool,
2119     generics_str_contains_newline: bool,
2120 ) -> Option<String> {
2121     let mut arg_item_strs = try_opt!(
2122         args.iter()
2123             .map(|arg| {
2124                 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2125             })
2126             .collect::<Option<Vec<_>>>()
2127     );
2128
2129     // Account for sugary self.
2130     // FIXME: the comment for the self argument is dropped. This is blocked
2131     // on rust issue #27522.
2132     let min_args = explicit_self
2133         .and_then(|explicit_self| {
2134             rewrite_explicit_self(explicit_self, args, context)
2135         })
2136         .map_or(1, |self_str| {
2137             arg_item_strs[0] = self_str;
2138             2
2139         });
2140
2141     // Comments between args.
2142     let mut arg_items = Vec::new();
2143     if min_args == 2 {
2144         arg_items.push(ListItem::from_str(""));
2145     }
2146
2147     // FIXME(#21): if there are no args, there might still be a comment, but
2148     // without spans for the comment or parens, there is no chance of
2149     // getting it right. You also don't get to put a comment on self, unless
2150     // it is explicit.
2151     if args.len() >= min_args || variadic {
2152         let comment_span_start = if min_args == 2 {
2153             let second_arg_start = if arg_has_pattern(&args[1]) {
2154                 args[1].pat.span.lo()
2155             } else {
2156                 args[1].ty.span.lo()
2157             };
2158             let reduced_span = mk_sp(span.lo(), second_arg_start);
2159
2160             context.codemap.span_after_last(reduced_span, ",")
2161         } else {
2162             span.lo()
2163         };
2164
2165         enum ArgumentKind<'a> {
2166             Regular(&'a ast::Arg),
2167             Variadic(BytePos),
2168         }
2169
2170         let variadic_arg = if variadic {
2171             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2172             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2173             Some(ArgumentKind::Variadic(variadic_start))
2174         } else {
2175             None
2176         };
2177
2178         let more_items = itemize_list(
2179             context.codemap,
2180             args[min_args - 1..]
2181                 .iter()
2182                 .map(ArgumentKind::Regular)
2183                 .chain(variadic_arg),
2184             ")",
2185             |arg| match *arg {
2186                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2187                 ArgumentKind::Variadic(start) => start,
2188             },
2189             |arg| match *arg {
2190                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2191                 ArgumentKind::Variadic(start) => start + BytePos(3),
2192             },
2193             |arg| match *arg {
2194                 ArgumentKind::Regular(..) => None,
2195                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2196             },
2197             comment_span_start,
2198             span.hi(),
2199             false,
2200         );
2201
2202         arg_items.extend(more_items);
2203     }
2204
2205     let fits_in_one_line = !generics_str_contains_newline &&
2206         (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2207
2208     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2209         item.item = Some(arg);
2210     }
2211
2212     let last_line_ends_with_comment = arg_items
2213         .iter()
2214         .last()
2215         .and_then(|item| item.post_comment.as_ref())
2216         .map_or(false, |s| s.trim().starts_with("//"));
2217
2218     let (indent, trailing_comma) = match context.config.fn_args_layout() {
2219         IndentStyle::Block if fits_in_one_line => {
2220             (indent.block_indent(context.config), SeparatorTactic::Never)
2221         }
2222         IndentStyle::Block => (
2223             indent.block_indent(context.config),
2224             context.config.trailing_comma(),
2225         ),
2226         IndentStyle::Visual if last_line_ends_with_comment => {
2227             (arg_indent, context.config.trailing_comma())
2228         }
2229         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2230     };
2231
2232     let tactic = definitive_tactic(
2233         &arg_items,
2234         context.config.fn_args_density().to_list_tactic(),
2235         Separator::Comma,
2236         one_line_budget,
2237     );
2238     let budget = match tactic {
2239         DefinitiveListTactic::Horizontal => one_line_budget,
2240         _ => multi_line_budget,
2241     };
2242
2243     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2244
2245     let fmt = ListFormatting {
2246         tactic: tactic,
2247         separator: ",",
2248         trailing_separator: if variadic {
2249             SeparatorTactic::Never
2250         } else {
2251             trailing_comma
2252         },
2253         separator_place: SeparatorPlace::Back,
2254         shape: Shape::legacy(budget, indent),
2255         ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2256         preserve_newline: true,
2257         config: context.config,
2258     };
2259
2260     write_list(&arg_items, &fmt)
2261 }
2262
2263 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2264     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2265         ident.node != symbol::keywords::Invalid.ident()
2266     } else {
2267         true
2268     }
2269 }
2270
2271 fn compute_budgets_for_args(
2272     context: &RewriteContext,
2273     result: &str,
2274     indent: Indent,
2275     ret_str_len: usize,
2276     newline_brace: bool,
2277     has_braces: bool,
2278     force_vertical_layout: bool,
2279 ) -> Option<((usize, usize, Indent))> {
2280     debug!(
2281         "compute_budgets_for_args {} {:?}, {}, {}",
2282         result.len(),
2283         indent,
2284         ret_str_len,
2285         newline_brace
2286     );
2287     // Try keeping everything on the same line.
2288     if !result.contains('\n') && !force_vertical_layout {
2289         // 2 = `()`, 3 = `() `, space is before ret_string.
2290         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2291         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2292         if has_braces {
2293             if !newline_brace {
2294                 // 2 = `{}`
2295                 used_space += 2;
2296             }
2297         } else {
2298             // 1 = `;`
2299             used_space += 1;
2300         }
2301         let one_line_budget = context
2302             .config
2303             .max_width()
2304             .checked_sub(used_space)
2305             .unwrap_or(0);
2306
2307         if one_line_budget > 0 {
2308             // 4 = "() {".len()
2309             let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2310                 IndentStyle::Block => {
2311                     let indent = indent.block_indent(context.config);
2312                     let budget =
2313                         try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2314                     (indent, budget)
2315                 }
2316                 IndentStyle::Visual => {
2317                     let indent = indent + result.len() + 1;
2318                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2319                     let budget =
2320                         try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2321                     (indent, budget)
2322                 }
2323             };
2324
2325             return Some((one_line_budget, multi_line_budget, indent));
2326         }
2327     }
2328
2329     // Didn't work. we must force vertical layout and put args on a newline.
2330     let new_indent = indent.block_indent(context.config);
2331     let used_space = match context.config.fn_args_layout() {
2332         // 1 = `,`
2333         IndentStyle::Block => new_indent.width() + 1,
2334         // Account for `)` and possibly ` {`.
2335         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2336     };
2337     let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2338     Some((0, max_space, new_indent))
2339 }
2340
2341 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2342     match (config.fn_brace_style(), config.where_density()) {
2343         (BraceStyle::AlwaysNextLine, _) => true,
2344         (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2345         (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2346         (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2347         _ => false,
2348     }
2349 }
2350
2351 fn rewrite_generics(
2352     context: &RewriteContext,
2353     generics: &ast::Generics,
2354     shape: Shape,
2355     span: Span,
2356 ) -> Option<String> {
2357     let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2358     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2359     rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2360         rewrite_generics_inner(context, generics, g_shape, 0, span)
2361     })
2362 }
2363
2364 fn rewrite_generics_inner(
2365     context: &RewriteContext,
2366     generics: &ast::Generics,
2367     shape: Shape,
2368     one_line_width: usize,
2369     span: Span,
2370 ) -> Option<String> {
2371     // FIXME: convert bounds to where clauses where they get too big or if
2372     // there is a where clause at all.
2373     let lifetimes: &[_] = &generics.lifetimes;
2374     let tys: &[_] = &generics.ty_params;
2375     if lifetimes.is_empty() && tys.is_empty() {
2376         return Some(String::new());
2377     }
2378
2379     // Strings for the generics.
2380     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2381     let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2382
2383     // Extract comments between generics.
2384     let lt_spans = lifetimes.iter().map(|l| {
2385         let hi = if l.bounds.is_empty() {
2386             l.lifetime.span.hi()
2387         } else {
2388             l.bounds[l.bounds.len() - 1].span.hi()
2389         };
2390         mk_sp(l.lifetime.span.lo(), hi)
2391     });
2392     let ty_spans = tys.iter().map(|ty| ty.span());
2393
2394     let items = itemize_list(
2395         context.codemap,
2396         lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2397         ">",
2398         |&(sp, _)| sp.lo(),
2399         |&(sp, _)| sp.hi(),
2400         // FIXME: don't clone
2401         |&(_, ref str)| str.clone(),
2402         context.codemap.span_after(span, "<"),
2403         span.hi(),
2404         false,
2405     );
2406     format_generics_item_list(context, items, shape, one_line_width)
2407 }
2408
2409 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2410     match config.generics_indent() {
2411         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2412         IndentStyle::Block => {
2413             // 1 = ","
2414             shape
2415                 .block()
2416                 .block_indent(config.tab_spaces())
2417                 .with_max_width(config)
2418                 .sub_width(1)
2419         }
2420     }
2421 }
2422
2423 pub fn format_generics_item_list<I>(
2424     context: &RewriteContext,
2425     items: I,
2426     shape: Shape,
2427     one_line_budget: usize,
2428 ) -> Option<String>
2429 where
2430     I: Iterator<Item = ListItem>,
2431 {
2432     let item_vec = items.collect::<Vec<_>>();
2433
2434     let tactic = definitive_tactic(
2435         &item_vec,
2436         ListTactic::HorizontalVertical,
2437         Separator::Comma,
2438         one_line_budget,
2439     );
2440     let fmt = ListFormatting {
2441         tactic: tactic,
2442         separator: ",",
2443         trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2444             SeparatorTactic::Never
2445         } else {
2446             context.config.trailing_comma()
2447         },
2448         separator_place: SeparatorPlace::Back,
2449         shape: shape,
2450         ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2451         preserve_newline: true,
2452         config: context.config,
2453     };
2454
2455     let list_str = try_opt!(write_list(&item_vec, &fmt));
2456
2457     Some(wrap_generics_with_angle_brackets(
2458         context,
2459         &list_str,
2460         shape.indent,
2461     ))
2462 }
2463
2464 pub fn wrap_generics_with_angle_brackets(
2465     context: &RewriteContext,
2466     list_str: &str,
2467     list_offset: Indent,
2468 ) -> String {
2469     if context.config.generics_indent() == IndentStyle::Block &&
2470         (list_str.contains('\n') || list_str.ends_with(','))
2471     {
2472         format!(
2473             "<\n{}{}\n{}>",
2474             list_offset.to_string(context.config),
2475             list_str,
2476             list_offset
2477                 .block_unindent(context.config)
2478                 .to_string(context.config)
2479         )
2480     } else if context.config.spaces_within_angle_brackets() {
2481         format!("< {} >", list_str)
2482     } else {
2483         format!("<{}>", list_str)
2484     }
2485 }
2486
2487 fn rewrite_trait_bounds(
2488     context: &RewriteContext,
2489     type_param_bounds: &ast::TyParamBounds,
2490     shape: Shape,
2491 ) -> Option<String> {
2492     let bounds: &[_] = type_param_bounds;
2493
2494     if bounds.is_empty() {
2495         return Some(String::new());
2496     }
2497     let bound_str = try_opt!(
2498         bounds
2499             .iter()
2500             .map(|ty_bound| ty_bound.rewrite(&context, shape))
2501             .collect::<Option<Vec<_>>>()
2502     );
2503     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2504 }
2505
2506 fn rewrite_where_clause_rfc_style(
2507     context: &RewriteContext,
2508     where_clause: &ast::WhereClause,
2509     shape: Shape,
2510     terminator: &str,
2511     span_end: Option<BytePos>,
2512     span_end_before_where: BytePos,
2513     where_clause_option: WhereClauseOption,
2514 ) -> Option<String> {
2515     let block_shape = shape.block().with_max_width(context.config);
2516
2517     let (span_before, span_after) =
2518         missing_span_before_after_where(span_end_before_where, where_clause);
2519     let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2520         context,
2521         span_before,
2522         span_after,
2523         shape,
2524     ));
2525
2526     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2527         " ".to_owned()
2528     } else {
2529         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2530     };
2531
2532     let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2533     // each clause on one line, trailing comma (except if suppress_comma)
2534     let span_start = where_clause.predicates[0].span().lo();
2535     // If we don't have the start of the next span, then use the end of the
2536     // predicates, but that means we miss comments.
2537     let len = where_clause.predicates.len();
2538     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2539     let span_end = span_end.unwrap_or(end_of_preds);
2540     let items = itemize_list(
2541         context.codemap,
2542         where_clause.predicates.iter(),
2543         terminator,
2544         |pred| pred.span().lo(),
2545         |pred| pred.span().hi(),
2546         |pred| pred.rewrite(context, block_shape),
2547         span_start,
2548         span_end,
2549         false,
2550     );
2551     let comma_tactic = if where_clause_option.suppress_comma {
2552         SeparatorTactic::Never
2553     } else {
2554         context.config.trailing_comma()
2555     };
2556
2557     let fmt = ListFormatting {
2558         tactic: DefinitiveListTactic::Vertical,
2559         separator: ",",
2560         trailing_separator: comma_tactic,
2561         separator_place: SeparatorPlace::Back,
2562         shape: clause_shape,
2563         ends_with_newline: true,
2564         preserve_newline: true,
2565         config: context.config,
2566     };
2567     let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2568
2569     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2570         String::new()
2571     } else {
2572         format!("\n{}", shape.indent.to_string(context.config))
2573     };
2574     let newline_before_where = comment_separator(&comment_before, shape);
2575     let newline_after_where = comment_separator(&comment_after, clause_shape);
2576
2577     // 6 = `where `
2578     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2579         comment_after.is_empty() && !preds_str.contains('\n') &&
2580         6 + preds_str.len() <= shape.width
2581     {
2582         String::from(" ")
2583     } else {
2584         format!("\n{}", clause_shape.indent.to_string(context.config))
2585     };
2586     Some(format!(
2587         "{}{}{}where{}{}{}{}",
2588         starting_newline,
2589         comment_before,
2590         newline_before_where,
2591         newline_after_where,
2592         comment_after,
2593         clause_sep,
2594         preds_str
2595     ))
2596 }
2597
2598 fn rewrite_where_clause(
2599     context: &RewriteContext,
2600     where_clause: &ast::WhereClause,
2601     brace_style: BraceStyle,
2602     shape: Shape,
2603     density: Density,
2604     terminator: &str,
2605     span_end: Option<BytePos>,
2606     span_end_before_where: BytePos,
2607     where_clause_option: WhereClauseOption,
2608 ) -> Option<String> {
2609     if where_clause.predicates.is_empty() {
2610         return Some(String::new());
2611     }
2612
2613     if context.config.where_style() == Style::Rfc {
2614         return rewrite_where_clause_rfc_style(
2615             context,
2616             where_clause,
2617             shape,
2618             terminator,
2619             span_end,
2620             span_end_before_where,
2621             where_clause_option,
2622         );
2623     }
2624
2625     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2626
2627     let offset = match context.config.where_pred_indent() {
2628         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2629         // 6 = "where ".len()
2630         IndentStyle::Visual => shape.indent + extra_indent + 6,
2631     };
2632     // FIXME: if where_pred_indent != Visual, then the budgets below might
2633     // be out by a char or two.
2634
2635     let budget = context.config.max_width() - offset.width();
2636     let span_start = where_clause.predicates[0].span().lo();
2637     // If we don't have the start of the next span, then use the end of the
2638     // predicates, but that means we miss comments.
2639     let len = where_clause.predicates.len();
2640     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2641     let span_end = span_end.unwrap_or(end_of_preds);
2642     let items = itemize_list(
2643         context.codemap,
2644         where_clause.predicates.iter(),
2645         terminator,
2646         |pred| pred.span().lo(),
2647         |pred| pred.span().hi(),
2648         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2649         span_start,
2650         span_end,
2651         false,
2652     );
2653     let item_vec = items.collect::<Vec<_>>();
2654     // FIXME: we don't need to collect here if the where_layout isn't
2655     // HorizontalVertical.
2656     let tactic = definitive_tactic(
2657         &item_vec,
2658         context.config.where_layout(),
2659         Separator::Comma,
2660         budget,
2661     );
2662
2663     let mut comma_tactic = context.config.trailing_comma();
2664     // Kind of a hack because we don't usually have trailing commas in where clauses.
2665     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2666         comma_tactic = SeparatorTactic::Never;
2667     }
2668
2669     let fmt = ListFormatting {
2670         tactic: tactic,
2671         separator: ",",
2672         trailing_separator: comma_tactic,
2673         separator_place: SeparatorPlace::Back,
2674         shape: Shape::legacy(budget, offset),
2675         ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2676         preserve_newline: true,
2677         config: context.config,
2678     };
2679     let preds_str = try_opt!(write_list(&item_vec, &fmt));
2680
2681     let end_length = if terminator == "{" {
2682         // If the brace is on the next line we don't need to count it otherwise it needs two
2683         // characters " {"
2684         match brace_style {
2685             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2686             BraceStyle::PreferSameLine => 2,
2687         }
2688     } else if terminator == "=" {
2689         2
2690     } else {
2691         terminator.len()
2692     };
2693     if density == Density::Tall || preds_str.contains('\n') ||
2694         shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2695     {
2696         Some(format!(
2697             "\n{}where {}",
2698             (shape.indent + extra_indent).to_string(context.config),
2699             preds_str
2700         ))
2701     } else {
2702         Some(format!(" where {}", preds_str))
2703     }
2704 }
2705
2706 fn missing_span_before_after_where(
2707     before_item_span_end: BytePos,
2708     where_clause: &ast::WhereClause,
2709 ) -> (Span, Span) {
2710     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2711     // 5 = `where`
2712     let pos_after_where = where_clause.span.lo() + BytePos(5);
2713     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2714     (missing_span_before, missing_span_after)
2715 }
2716
2717 fn rewrite_comments_before_after_where(
2718     context: &RewriteContext,
2719     span_before_where: Span,
2720     span_after_where: Span,
2721     shape: Shape,
2722 ) -> Option<(String, String)> {
2723     let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2724     let after_comment = try_opt!(rewrite_missing_comment(
2725         span_after_where,
2726         shape.block_indent(context.config.tab_spaces()),
2727         context,
2728     ));
2729     Some((before_comment, after_comment))
2730 }
2731
2732 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2733     format!("{}{}{}", format_visibility(vis), item_name, ident)
2734 }
2735
2736 fn format_generics(
2737     context: &RewriteContext,
2738     generics: &ast::Generics,
2739     opener: &str,
2740     terminator: &str,
2741     brace_style: BraceStyle,
2742     force_same_line_brace: bool,
2743     offset: Indent,
2744     span: Span,
2745     used_width: usize,
2746 ) -> Option<String> {
2747     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2748     let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2749
2750     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2751         let budget = context
2752             .config
2753             .max_width()
2754             .checked_sub(last_line_used_width(&result, offset.width()))
2755             .unwrap_or(0);
2756         let option = WhereClauseOption::snuggled(&result);
2757         let where_clause_str = try_opt!(rewrite_where_clause(
2758             context,
2759             &generics.where_clause,
2760             brace_style,
2761             Shape::legacy(budget, offset.block_only()),
2762             Density::Tall,
2763             terminator,
2764             Some(span.hi()),
2765             generics.span.hi(),
2766             option,
2767         ));
2768         result.push_str(&where_clause_str);
2769         force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2770             (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2771     } else {
2772         force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2773             brace_style != BraceStyle::AlwaysNextLine
2774     };
2775     let total_used_width = last_line_used_width(&result, used_width);
2776     let remaining_budget = context
2777         .config
2778         .max_width()
2779         .checked_sub(total_used_width)
2780         .unwrap_or(0);
2781     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2782     // and hence we take the closer into account as well for one line budget.
2783     // We assume that the closer has the same length as the opener.
2784     let overhead = if force_same_line_brace {
2785         1 + opener.len() + opener.len()
2786     } else {
2787         1 + opener.len()
2788     };
2789     let forbid_same_line_brace = overhead > remaining_budget;
2790     if !forbid_same_line_brace && same_line_brace {
2791         result.push(' ');
2792     } else {
2793         result.push('\n');
2794         result.push_str(&offset.block_only().to_string(context.config));
2795     }
2796     result.push_str(opener);
2797
2798     Some(result)
2799 }
2800
2801 impl Rewrite for ast::ForeignItem {
2802     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2803         let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2804         // Drop semicolon or it will be interpreted as comment.
2805         // FIXME: this may be a faulty span from libsyntax.
2806         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2807
2808         let item_str = try_opt!(match self.node {
2809             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2810                 rewrite_fn_base(
2811                     context,
2812                     shape.indent,
2813                     self.ident,
2814                     fn_decl,
2815                     generics,
2816                     ast::Unsafety::Normal,
2817                     ast::Constness::NotConst,
2818                     ast::Defaultness::Final,
2819                     // These are not actually rust functions,
2820                     // but we format them as such.
2821                     abi::Abi::Rust,
2822                     &self.vis,
2823                     span,
2824                     false,
2825                     false,
2826                     false,
2827                 ).map(|(s, _)| format!("{};", s))
2828             }
2829             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2830                 // FIXME(#21): we're dropping potential comments in between the
2831                 // function keywords here.
2832                 let vis = format_visibility(&self.vis);
2833                 let mut_str = if is_mutable { "mut " } else { "" };
2834                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2835                 // 1 = ;
2836                 let shape = try_opt!(shape.sub_width(1));
2837                 ty.rewrite(context, shape).map(|ty_str| {
2838                     // 1 = space between prefix and type.
2839                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2840                         String::from(" ")
2841                     } else {
2842                         let nested_indent = shape.indent.block_indent(context.config);
2843                         format!("\n{}", nested_indent.to_string(context.config))
2844                     };
2845                     format!("{}{}{};", prefix, sep, ty_str)
2846                 })
2847             }
2848         });
2849
2850         let missing_span = if self.attrs.is_empty() {
2851             mk_sp(self.span.lo(), self.span.lo())
2852         } else {
2853             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2854         };
2855         combine_strs_with_missing_comments(
2856             context,
2857             &attrs_str,
2858             &item_str,
2859             missing_span,
2860             shape,
2861             false,
2862         )
2863     }
2864 }