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