]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Add StaticParts to reduce the number of args in rewrite_static()
[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 struct StaticParts<'a> {
1465     vis: &'a ast::Visibility,
1466     ident: ast::Ident,
1467     ty: &'a ast::Ty,
1468     mutability: ast::Mutability,
1469     expr_opt: Option<&'a ptr::P<ast::Expr>>,
1470 }
1471
1472 impl<'a> StaticParts<'a> {
1473     pub fn new(
1474         vis: &'a ast::Visibility,
1475         ident: ast::Ident,
1476         ty: &'a ast::Ty,
1477         mutability: ast::Mutability,
1478         expr_opt: Option<&'a ptr::P<ast::Expr>>,
1479     ) -> StaticParts<'a> {
1480         StaticParts {
1481             vis,
1482             ident,
1483             ty,
1484             mutability,
1485             expr_opt,
1486         }
1487     }
1488 }
1489
1490 pub fn rewrite_static(
1491     prefix: &str,
1492     static_parts: &StaticParts,
1493     offset: Indent,
1494     span: Span,
1495     context: &RewriteContext,
1496 ) -> Option<String> {
1497     let StaticParts {
1498         vis,
1499         ident,
1500         ty,
1501         mutability,
1502         expr_opt,
1503     } = *static_parts;
1504     let colon = colon_spaces(
1505         context.config.space_before_type_annotation(),
1506         context.config.space_after_type_annotation_colon(),
1507     );
1508     let prefix = format!(
1509         "{}{} {}{}{}",
1510         format_visibility(vis),
1511         prefix,
1512         format_mutability(mutability),
1513         ident,
1514         colon,
1515     );
1516     // 2 = " =".len()
1517     let ty_str = ty.rewrite(
1518         context,
1519         Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1520     )?;
1521
1522     if let Some(expr) = expr_opt {
1523         let lhs = format!("{}{} =", prefix, ty_str);
1524         // 1 = ;
1525         let remaining_width = context.budget(offset.block_indent + 1);
1526         rewrite_assign_rhs(
1527             context,
1528             lhs,
1529             expr,
1530             Shape::legacy(remaining_width, offset.block_only()),
1531         ).and_then(|res| recover_comment_removed(res, span, context))
1532             .map(|s| if s.ends_with(';') { s } else { s + ";" })
1533     } else {
1534         Some(format!("{}{};", prefix, ty_str))
1535     }
1536 }
1537
1538 pub fn rewrite_associated_type(
1539     ident: ast::Ident,
1540     ty_opt: Option<&ptr::P<ast::Ty>>,
1541     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1542     context: &RewriteContext,
1543     indent: Indent,
1544 ) -> Option<String> {
1545     let prefix = format!("type {}", ident);
1546
1547     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1548         // 2 = ": ".len()
1549         let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1550         let bounds: &[_] = ty_param_bounds;
1551         let bound_str = bounds
1552             .iter()
1553             .map(|ty_bound| ty_bound.rewrite(context, shape))
1554             .collect::<Option<Vec<_>>>()?;
1555         if !bounds.is_empty() {
1556             format!(": {}", join_bounds(context, shape, &bound_str))
1557         } else {
1558             String::new()
1559         }
1560     } else {
1561         String::new()
1562     };
1563
1564     if let Some(ty) = ty_opt {
1565         let ty_str = ty.rewrite(
1566             context,
1567             Shape::legacy(
1568                 context.budget(indent.block_indent + prefix.len() + 2),
1569                 indent.block_only(),
1570             ),
1571         )?;
1572         Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1573     } else {
1574         Some(format!("{}{};", prefix, type_bounds_str))
1575     }
1576 }
1577
1578 pub fn rewrite_associated_impl_type(
1579     ident: ast::Ident,
1580     defaultness: ast::Defaultness,
1581     ty_opt: Option<&ptr::P<ast::Ty>>,
1582     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1583     context: &RewriteContext,
1584     indent: Indent,
1585 ) -> Option<String> {
1586     let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1587
1588     match defaultness {
1589         ast::Defaultness::Default => Some(format!("default {}", result)),
1590         _ => Some(result),
1591     }
1592 }
1593
1594 impl Rewrite for ast::FunctionRetTy {
1595     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1596         match *self {
1597             ast::FunctionRetTy::Default(_) => Some(String::new()),
1598             ast::FunctionRetTy::Ty(ref ty) => {
1599                 let inner_width = shape.width.checked_sub(3)?;
1600                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1601                     .map(|r| format!("-> {}", r))
1602             }
1603         }
1604     }
1605 }
1606
1607 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1608     match ty.node {
1609         ast::TyKind::Infer => {
1610             let original = context.snippet(ty.span);
1611             original != "_"
1612         }
1613         _ => false,
1614     }
1615 }
1616
1617 impl Rewrite for ast::Arg {
1618     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1619         if is_named_arg(self) {
1620             let mut result = self.pat
1621                 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1622
1623             if !is_empty_infer(context, &*self.ty) {
1624                 if context.config.space_before_type_annotation() {
1625                     result.push_str(" ");
1626                 }
1627                 result.push_str(":");
1628                 if context.config.space_after_type_annotation_colon() {
1629                     result.push_str(" ");
1630                 }
1631                 let overhead = last_line_width(&result);
1632                 let max_width = shape.width.checked_sub(overhead)?;
1633                 let ty_str = self.ty
1634                     .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1635                 result.push_str(&ty_str);
1636             }
1637
1638             Some(result)
1639         } else {
1640             self.ty.rewrite(context, shape)
1641         }
1642     }
1643 }
1644
1645 fn rewrite_explicit_self(
1646     explicit_self: &ast::ExplicitSelf,
1647     args: &[ast::Arg],
1648     context: &RewriteContext,
1649 ) -> Option<String> {
1650     match explicit_self.node {
1651         ast::SelfKind::Region(lt, m) => {
1652             let mut_str = format_mutability(m);
1653             match lt {
1654                 Some(ref l) => {
1655                     let lifetime_str = l.rewrite(
1656                         context,
1657                         Shape::legacy(context.config.max_width(), Indent::empty()),
1658                     )?;
1659                     Some(format!("&{} {}self", lifetime_str, mut_str))
1660                 }
1661                 None => Some(format!("&{}self", mut_str)),
1662             }
1663         }
1664         ast::SelfKind::Explicit(ref ty, _) => {
1665             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1666
1667             let mutability = explicit_self_mutability(&args[0]);
1668             let type_str = ty.rewrite(
1669                 context,
1670                 Shape::legacy(context.config.max_width(), Indent::empty()),
1671             )?;
1672
1673             Some(format!(
1674                 "{}self: {}",
1675                 format_mutability(mutability),
1676                 type_str
1677             ))
1678         }
1679         ast::SelfKind::Value(_) => {
1680             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1681
1682             let mutability = explicit_self_mutability(&args[0]);
1683
1684             Some(format!("{}self", format_mutability(mutability)))
1685         }
1686     }
1687 }
1688
1689 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1690 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1691 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1692     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1693         mutability
1694     } else {
1695         unreachable!()
1696     }
1697 }
1698
1699 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1700     if is_named_arg(arg) {
1701         arg.pat.span.lo()
1702     } else {
1703         arg.ty.span.lo()
1704     }
1705 }
1706
1707 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1708     match arg.ty.node {
1709         ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1710         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1711         _ => arg.ty.span.hi(),
1712     }
1713 }
1714
1715 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1716     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1717         ident.node != symbol::keywords::Invalid.ident()
1718     } else {
1719         true
1720     }
1721 }
1722
1723 // Return type is (result, force_new_line_for_brace)
1724 fn rewrite_fn_base(
1725     context: &RewriteContext,
1726     indent: Indent,
1727     ident: ast::Ident,
1728     fn_sig: &FnSig,
1729     span: Span,
1730     newline_brace: bool,
1731     has_body: bool,
1732 ) -> Option<(String, bool)> {
1733     let mut force_new_line_for_brace = false;
1734
1735     let where_clause = &fn_sig.generics.where_clause;
1736
1737     let mut result = String::with_capacity(1024);
1738     result.push_str(&fn_sig.to_str(context));
1739
1740     // fn foo
1741     result.push_str("fn ");
1742     result.push_str(&ident.to_string());
1743
1744     // Generics.
1745     let overhead = if has_body && !newline_brace {
1746         // 4 = `() {`
1747         4
1748     } else {
1749         // 2 = `()`
1750         2
1751     };
1752     let used_width = last_line_used_width(&result, indent.width());
1753     let one_line_budget = context.budget(used_width + overhead);
1754     let shape = Shape {
1755         width: one_line_budget,
1756         indent: indent,
1757         offset: used_width,
1758     };
1759     let fd = fn_sig.decl;
1760     let g_span = mk_sp(span.lo(), fd.output.span().lo());
1761     let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1762     result.push_str(&generics_str);
1763
1764     let snuggle_angle_bracket = generics_str
1765         .lines()
1766         .last()
1767         .map_or(false, |l| l.trim_left().len() == 1);
1768
1769     // Note that the width and indent don't really matter, we'll re-layout the
1770     // return type later anyway.
1771     let ret_str = fd.output
1772         .rewrite(context, Shape::indented(indent, context.config))?;
1773
1774     let multi_line_ret_str = ret_str.contains('\n');
1775     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1776
1777     // Args.
1778     let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1779         context,
1780         &result,
1781         indent,
1782         ret_str_len,
1783         newline_brace,
1784         has_body,
1785         multi_line_ret_str,
1786     )?;
1787
1788     debug!(
1789         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1790         one_line_budget,
1791         multi_line_budget,
1792         arg_indent
1793     );
1794
1795     // Check if vertical layout was forced.
1796     if one_line_budget == 0 {
1797         if snuggle_angle_bracket {
1798             result.push('(');
1799         } else if context.config.fn_args_paren_newline() {
1800             result.push('\n');
1801             result.push_str(&arg_indent.to_string(context.config));
1802             if context.config.fn_args_indent() == IndentStyle::Visual {
1803                 arg_indent = arg_indent + 1; // extra space for `(`
1804             }
1805             result.push('(');
1806         } else {
1807             result.push_str("(");
1808             if context.config.fn_args_indent() == IndentStyle::Visual {
1809                 result.push('\n');
1810                 result.push_str(&arg_indent.to_string(context.config));
1811             }
1812         }
1813     } else {
1814         result.push('(');
1815     }
1816     if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1817         result.push(' ')
1818     }
1819
1820     // Skip `pub(crate)`.
1821     let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1822     // A conservative estimation, to goal is to be over all parens in generics
1823     let args_start = fn_sig
1824         .generics
1825         .ty_params
1826         .last()
1827         .map_or(lo_after_visibility, |tp| end_typaram(tp));
1828     let args_end = if fd.inputs.is_empty() {
1829         context
1830             .codemap
1831             .span_after(mk_sp(args_start, span.hi()), ")")
1832     } else {
1833         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1834         context.codemap.span_after(last_span, ")")
1835     };
1836     let args_span = mk_sp(
1837         context
1838             .codemap
1839             .span_after(mk_sp(args_start, span.hi()), "("),
1840         args_end,
1841     );
1842     let arg_str = rewrite_args(
1843         context,
1844         &fd.inputs,
1845         fd.get_self().as_ref(),
1846         one_line_budget,
1847         multi_line_budget,
1848         indent,
1849         arg_indent,
1850         args_span,
1851         fd.variadic,
1852         generics_str.contains('\n'),
1853     )?;
1854
1855     let put_args_in_block = match context.config.fn_args_indent() {
1856         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1857         _ => false,
1858     } && !fd.inputs.is_empty();
1859
1860     let mut args_last_line_contains_comment = false;
1861     if put_args_in_block {
1862         arg_indent = indent.block_indent(context.config);
1863         result.push('\n');
1864         result.push_str(&arg_indent.to_string(context.config));
1865         result.push_str(&arg_str);
1866         result.push('\n');
1867         result.push_str(&indent.to_string(context.config));
1868         result.push(')');
1869     } else {
1870         result.push_str(&arg_str);
1871         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1872         // Put the closing brace on the next line if it overflows the max width.
1873         // 1 = `)`
1874         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1875             result.push('\n');
1876         }
1877         if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1878             result.push(' ')
1879         }
1880         // If the last line of args contains comment, we cannot put the closing paren
1881         // on the same line.
1882         if arg_str
1883             .lines()
1884             .last()
1885             .map_or(false, |last_line| last_line.contains("//"))
1886         {
1887             args_last_line_contains_comment = true;
1888             result.push('\n');
1889             result.push_str(&arg_indent.to_string(context.config));
1890         }
1891         result.push(')');
1892     }
1893
1894     // Return type.
1895     if let ast::FunctionRetTy::Ty(..) = fd.output {
1896         let ret_should_indent = match context.config.fn_args_indent() {
1897             // If our args are block layout then we surely must have space.
1898             IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1899             _ if args_last_line_contains_comment => false,
1900             _ if result.contains('\n') || multi_line_ret_str => true,
1901             _ => {
1902                 // If the return type would push over the max width, then put the return type on
1903                 // a new line. With the +1 for the signature length an additional space between
1904                 // the closing parenthesis of the argument and the arrow '->' is considered.
1905                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1906
1907                 // If there is no where clause, take into account the space after the return type
1908                 // and the brace.
1909                 if where_clause.predicates.is_empty() {
1910                     sig_length += 2;
1911                 }
1912
1913                 sig_length > context.config.max_width()
1914             }
1915         };
1916         let ret_indent = if ret_should_indent {
1917             let indent = match context.config.fn_return_indent() {
1918                 ReturnIndent::WithWhereClause => indent + 4,
1919                 // Aligning with non-existent args looks silly.
1920                 _ if arg_str.is_empty() => {
1921                     force_new_line_for_brace = true;
1922                     indent + 4
1923                 }
1924                 // FIXME: we might want to check that using the arg indent
1925                 // doesn't blow our budget, and if it does, then fallback to
1926                 // the where clause indent.
1927                 _ => arg_indent,
1928             };
1929
1930             result.push('\n');
1931             result.push_str(&indent.to_string(context.config));
1932             indent
1933         } else {
1934             result.push(' ');
1935             Indent::new(indent.block_indent, last_line_width(&result))
1936         };
1937
1938         if multi_line_ret_str || ret_should_indent {
1939             // Now that we know the proper indent and width, we need to
1940             // re-layout the return type.
1941             let ret_str = fd.output
1942                 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1943             result.push_str(&ret_str);
1944         } else {
1945             result.push_str(&ret_str);
1946         }
1947
1948         // Comment between return type and the end of the decl.
1949         let snippet_lo = fd.output.span().hi();
1950         if where_clause.predicates.is_empty() {
1951             let snippet_hi = span.hi();
1952             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1953             // Try to preserve the layout of the original snippet.
1954             let original_starts_with_newline = snippet
1955                 .find(|c| c != ' ')
1956                 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1957             let original_ends_with_newline = snippet
1958                 .rfind(|c| c != ' ')
1959                 .map_or(false, |i| snippet[i..].ends_with('\n'));
1960             let snippet = snippet.trim();
1961             if !snippet.is_empty() {
1962                 result.push(if original_starts_with_newline {
1963                     '\n'
1964                 } else {
1965                     ' '
1966                 });
1967                 result.push_str(snippet);
1968                 if original_ends_with_newline {
1969                     force_new_line_for_brace = true;
1970                 }
1971             }
1972         }
1973     }
1974
1975     let should_compress_where = match context.config.where_density() {
1976         Density::Compressed => !result.contains('\n'),
1977         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1978         _ => false,
1979     };
1980
1981     let pos_before_where = match fd.output {
1982         ast::FunctionRetTy::Default(..) => args_span.hi(),
1983         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1984     };
1985
1986     let is_args_multi_lined = arg_str.contains('\n');
1987
1988     if where_clause.predicates.len() == 1 && should_compress_where {
1989         let budget = context.budget(last_line_used_width(&result, indent.width()));
1990         if let Some(where_clause_str) = rewrite_where_clause(
1991             context,
1992             where_clause,
1993             context.config.fn_brace_style(),
1994             Shape::legacy(budget, indent),
1995             Density::Compressed,
1996             "{",
1997             Some(span.hi()),
1998             pos_before_where,
1999             WhereClauseOption::compressed(),
2000             is_args_multi_lined,
2001         ) {
2002             result.push_str(&where_clause_str);
2003             force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2004             return Some((result, force_new_line_for_brace));
2005         }
2006     }
2007
2008     let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2009     let where_clause_str = rewrite_where_clause(
2010         context,
2011         where_clause,
2012         context.config.fn_brace_style(),
2013         Shape::indented(indent, context.config),
2014         Density::Tall,
2015         "{",
2016         Some(span.hi()),
2017         pos_before_where,
2018         option,
2019         is_args_multi_lined,
2020     )?;
2021     // If there are neither where clause nor return type, we may be missing comments between
2022     // args and `{`.
2023     if where_clause_str.is_empty() {
2024         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2025             match recover_missing_comment_in_span(
2026                 mk_sp(args_span.hi(), ret_span.hi()),
2027                 shape,
2028                 context,
2029                 last_line_width(&result),
2030             ) {
2031                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2032                     result.push_str(missing_comment);
2033                     force_new_line_for_brace = true;
2034                 }
2035                 _ => (),
2036             }
2037         }
2038     }
2039
2040     result.push_str(&where_clause_str);
2041
2042     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2043     force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2044     Some((result, force_new_line_for_brace))
2045 }
2046
2047 #[derive(Copy, Clone)]
2048 struct WhereClauseOption {
2049     suppress_comma: bool, // Force no trailing comma
2050     snuggle: bool,        // Do not insert newline before `where`
2051     compress_where: bool, // Try single line where clause instead of vertical layout
2052 }
2053
2054 impl WhereClauseOption {
2055     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2056         WhereClauseOption {
2057             suppress_comma: suppress_comma,
2058             snuggle: snuggle,
2059             compress_where: false,
2060         }
2061     }
2062
2063     pub fn compressed() -> WhereClauseOption {
2064         WhereClauseOption {
2065             suppress_comma: true,
2066             snuggle: false,
2067             compress_where: true,
2068         }
2069     }
2070
2071     pub fn snuggled(current: &str) -> WhereClauseOption {
2072         WhereClauseOption {
2073             suppress_comma: false,
2074             snuggle: trimmed_last_line_width(current) == 1,
2075             compress_where: false,
2076         }
2077     }
2078 }
2079
2080 fn rewrite_args(
2081     context: &RewriteContext,
2082     args: &[ast::Arg],
2083     explicit_self: Option<&ast::ExplicitSelf>,
2084     one_line_budget: usize,
2085     multi_line_budget: usize,
2086     indent: Indent,
2087     arg_indent: Indent,
2088     span: Span,
2089     variadic: bool,
2090     generics_str_contains_newline: bool,
2091 ) -> Option<String> {
2092     let mut arg_item_strs = args.iter()
2093         .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2094         .collect::<Option<Vec<_>>>()?;
2095
2096     // Account for sugary self.
2097     // FIXME: the comment for the self argument is dropped. This is blocked
2098     // on rust issue #27522.
2099     let min_args = explicit_self
2100         .and_then(|explicit_self| {
2101             rewrite_explicit_self(explicit_self, args, context)
2102         })
2103         .map_or(1, |self_str| {
2104             arg_item_strs[0] = self_str;
2105             2
2106         });
2107
2108     // Comments between args.
2109     let mut arg_items = Vec::new();
2110     if min_args == 2 {
2111         arg_items.push(ListItem::from_str(""));
2112     }
2113
2114     // FIXME(#21): if there are no args, there might still be a comment, but
2115     // without spans for the comment or parens, there is no chance of
2116     // getting it right. You also don't get to put a comment on self, unless
2117     // it is explicit.
2118     if args.len() >= min_args || variadic {
2119         let comment_span_start = if min_args == 2 {
2120             let second_arg_start = if arg_has_pattern(&args[1]) {
2121                 args[1].pat.span.lo()
2122             } else {
2123                 args[1].ty.span.lo()
2124             };
2125             let reduced_span = mk_sp(span.lo(), second_arg_start);
2126
2127             context.codemap.span_after_last(reduced_span, ",")
2128         } else {
2129             span.lo()
2130         };
2131
2132         enum ArgumentKind<'a> {
2133             Regular(&'a ast::Arg),
2134             Variadic(BytePos),
2135         }
2136
2137         let variadic_arg = if variadic {
2138             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2139             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2140             Some(ArgumentKind::Variadic(variadic_start))
2141         } else {
2142             None
2143         };
2144
2145         let more_items = itemize_list(
2146             context.codemap,
2147             args[min_args - 1..]
2148                 .iter()
2149                 .map(ArgumentKind::Regular)
2150                 .chain(variadic_arg),
2151             ")",
2152             |arg| match *arg {
2153                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2154                 ArgumentKind::Variadic(start) => start,
2155             },
2156             |arg| match *arg {
2157                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2158                 ArgumentKind::Variadic(start) => start + BytePos(3),
2159             },
2160             |arg| match *arg {
2161                 ArgumentKind::Regular(..) => None,
2162                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2163             },
2164             comment_span_start,
2165             span.hi(),
2166             false,
2167         );
2168
2169         arg_items.extend(more_items);
2170     }
2171
2172     let fits_in_one_line = !generics_str_contains_newline
2173         && (arg_items.is_empty()
2174             || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2175
2176     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2177         item.item = Some(arg);
2178     }
2179
2180     let last_line_ends_with_comment = arg_items
2181         .iter()
2182         .last()
2183         .and_then(|item| item.post_comment.as_ref())
2184         .map_or(false, |s| s.trim().starts_with("//"));
2185
2186     let (indent, trailing_comma) = match context.config.fn_args_indent() {
2187         IndentStyle::Block if fits_in_one_line => {
2188             (indent.block_indent(context.config), SeparatorTactic::Never)
2189         }
2190         IndentStyle::Block => (
2191             indent.block_indent(context.config),
2192             context.config.trailing_comma(),
2193         ),
2194         IndentStyle::Visual if last_line_ends_with_comment => {
2195             (arg_indent, context.config.trailing_comma())
2196         }
2197         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2198     };
2199
2200     let tactic = definitive_tactic(
2201         &arg_items,
2202         context.config.fn_args_density().to_list_tactic(),
2203         Separator::Comma,
2204         one_line_budget,
2205     );
2206     let budget = match tactic {
2207         DefinitiveListTactic::Horizontal => one_line_budget,
2208         _ => multi_line_budget,
2209     };
2210
2211     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2212
2213     let fmt = ListFormatting {
2214         tactic: tactic,
2215         separator: ",",
2216         trailing_separator: if variadic {
2217             SeparatorTactic::Never
2218         } else {
2219             trailing_comma
2220         },
2221         separator_place: SeparatorPlace::Back,
2222         shape: Shape::legacy(budget, indent),
2223         ends_with_newline: tactic.ends_with_newline(context.config.fn_args_indent()),
2224         preserve_newline: true,
2225         config: context.config,
2226     };
2227
2228     write_list(&arg_items, &fmt)
2229 }
2230
2231 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2232     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2233         ident.node != symbol::keywords::Invalid.ident()
2234     } else {
2235         true
2236     }
2237 }
2238
2239 fn compute_budgets_for_args(
2240     context: &RewriteContext,
2241     result: &str,
2242     indent: Indent,
2243     ret_str_len: usize,
2244     newline_brace: bool,
2245     has_braces: bool,
2246     force_vertical_layout: bool,
2247 ) -> Option<((usize, usize, Indent))> {
2248     debug!(
2249         "compute_budgets_for_args {} {:?}, {}, {}",
2250         result.len(),
2251         indent,
2252         ret_str_len,
2253         newline_brace
2254     );
2255     // Try keeping everything on the same line.
2256     if !result.contains('\n') && !force_vertical_layout {
2257         // 2 = `()`, 3 = `() `, space is before ret_string.
2258         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2259         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2260         if has_braces {
2261             if !newline_brace {
2262                 // 2 = `{}`
2263                 used_space += 2;
2264             }
2265         } else {
2266             // 1 = `;`
2267             used_space += 1;
2268         }
2269         let one_line_budget = context.budget(used_space);
2270
2271         if one_line_budget > 0 {
2272             // 4 = "() {".len()
2273             let (indent, multi_line_budget) = match context.config.fn_args_indent() {
2274                 IndentStyle::Block => {
2275                     let indent = indent.block_indent(context.config);
2276                     (indent, context.budget(indent.width() + 1))
2277                 }
2278                 IndentStyle::Visual => {
2279                     let indent = indent + result.len() + 1;
2280                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2281                     (indent, context.budget(multi_line_overhead))
2282                 }
2283             };
2284
2285             return Some((one_line_budget, multi_line_budget, indent));
2286         }
2287     }
2288
2289     // Didn't work. we must force vertical layout and put args on a newline.
2290     let new_indent = indent.block_indent(context.config);
2291     let used_space = match context.config.fn_args_indent() {
2292         // 1 = `,`
2293         IndentStyle::Block => new_indent.width() + 1,
2294         // Account for `)` and possibly ` {`.
2295         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2296     };
2297     Some((0, context.budget(used_space), new_indent))
2298 }
2299
2300 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2301     let predicate_count = where_clause.predicates.len();
2302
2303     if config.where_single_line() && predicate_count == 1 {
2304         return false;
2305     }
2306     match (config.fn_brace_style(), config.where_density()) {
2307         (BraceStyle::AlwaysNextLine, _) => true,
2308         (_, Density::Compressed) if predicate_count == 1 => false,
2309         (_, Density::CompressedIfEmpty) if predicate_count == 1 && !has_body => false,
2310         (BraceStyle::SameLineWhere, _) if predicate_count > 0 => true,
2311         _ => false,
2312     }
2313 }
2314
2315 fn rewrite_generics(
2316     context: &RewriteContext,
2317     generics: &ast::Generics,
2318     shape: Shape,
2319     span: Span,
2320 ) -> Option<String> {
2321     let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2322     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2323     rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2324         rewrite_generics_inner(context, generics, g_shape, 0, span)
2325     })
2326 }
2327
2328 fn rewrite_generics_inner(
2329     context: &RewriteContext,
2330     generics: &ast::Generics,
2331     shape: Shape,
2332     one_line_width: usize,
2333     span: Span,
2334 ) -> Option<String> {
2335     // FIXME: convert bounds to where clauses where they get too big or if
2336     // there is a where clause at all.
2337
2338     // Wrapper type
2339     enum GenericsArg<'a> {
2340         Lifetime(&'a ast::LifetimeDef),
2341         TyParam(&'a ast::TyParam),
2342     }
2343     impl<'a> Rewrite for GenericsArg<'a> {
2344         fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2345             match *self {
2346                 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2347                 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2348             }
2349         }
2350     }
2351     impl<'a> Spanned for GenericsArg<'a> {
2352         fn span(&self) -> Span {
2353             match *self {
2354                 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2355                 GenericsArg::TyParam(ty) => ty.span(),
2356             }
2357         }
2358     }
2359
2360     if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2361         return Some(String::new());
2362     }
2363
2364     let generics_args = generics
2365         .lifetimes
2366         .iter()
2367         .map(|lt| GenericsArg::Lifetime(lt))
2368         .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2369     let items = itemize_list(
2370         context.codemap,
2371         generics_args,
2372         ">",
2373         |arg| arg.span().lo(),
2374         |arg| arg.span().hi(),
2375         |arg| arg.rewrite(context, shape),
2376         context.codemap.span_after(span, "<"),
2377         span.hi(),
2378         false,
2379     );
2380     format_generics_item_list(context, items, shape, one_line_width)
2381 }
2382
2383 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2384     match config.generics_indent() {
2385         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2386         IndentStyle::Block => {
2387             // 1 = ","
2388             shape
2389                 .block()
2390                 .block_indent(config.tab_spaces())
2391                 .with_max_width(config)
2392                 .sub_width(1)
2393         }
2394     }
2395 }
2396
2397 pub fn format_generics_item_list<I>(
2398     context: &RewriteContext,
2399     items: I,
2400     shape: Shape,
2401     one_line_budget: usize,
2402 ) -> Option<String>
2403 where
2404     I: Iterator<Item = ListItem>,
2405 {
2406     let item_vec = items.collect::<Vec<_>>();
2407
2408     let tactic = definitive_tactic(
2409         &item_vec,
2410         ListTactic::HorizontalVertical,
2411         Separator::Comma,
2412         one_line_budget,
2413     );
2414     let fmt = ListFormatting {
2415         tactic: tactic,
2416         separator: ",",
2417         trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2418             SeparatorTactic::Never
2419         } else {
2420             context.config.trailing_comma()
2421         },
2422         separator_place: SeparatorPlace::Back,
2423         shape: shape,
2424         ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2425         preserve_newline: true,
2426         config: context.config,
2427     };
2428
2429     let list_str = write_list(&item_vec, &fmt)?;
2430
2431     Some(wrap_generics_with_angle_brackets(
2432         context,
2433         &list_str,
2434         shape.indent,
2435     ))
2436 }
2437
2438 pub fn wrap_generics_with_angle_brackets(
2439     context: &RewriteContext,
2440     list_str: &str,
2441     list_offset: Indent,
2442 ) -> String {
2443     if context.config.generics_indent() == IndentStyle::Block
2444         && (list_str.contains('\n') || list_str.ends_with(','))
2445     {
2446         format!(
2447             "<\n{}{}\n{}>",
2448             list_offset.to_string(context.config),
2449             list_str,
2450             list_offset
2451                 .block_unindent(context.config)
2452                 .to_string(context.config)
2453         )
2454     } else if context.config.spaces_within_angle_brackets() {
2455         format!("< {} >", list_str)
2456     } else {
2457         format!("<{}>", list_str)
2458     }
2459 }
2460
2461 fn rewrite_trait_bounds(
2462     context: &RewriteContext,
2463     type_param_bounds: &ast::TyParamBounds,
2464     shape: Shape,
2465 ) -> Option<String> {
2466     let bounds: &[_] = type_param_bounds;
2467
2468     if bounds.is_empty() {
2469         return Some(String::new());
2470     }
2471     let bound_str = bounds
2472         .iter()
2473         .map(|ty_bound| ty_bound.rewrite(context, shape))
2474         .collect::<Option<Vec<_>>>()?;
2475     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2476 }
2477
2478 fn rewrite_where_clause_rfc_style(
2479     context: &RewriteContext,
2480     where_clause: &ast::WhereClause,
2481     shape: Shape,
2482     terminator: &str,
2483     span_end: Option<BytePos>,
2484     span_end_before_where: BytePos,
2485     where_clause_option: WhereClauseOption,
2486     is_args_multi_line: bool,
2487 ) -> Option<String> {
2488     let block_shape = shape.block().with_max_width(context.config);
2489
2490     let (span_before, span_after) =
2491         missing_span_before_after_where(span_end_before_where, where_clause);
2492     let (comment_before, comment_after) =
2493         rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2494
2495     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2496         " ".to_owned()
2497     } else {
2498         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2499     };
2500
2501     let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2502     // 1 = `,`
2503     let clause_shape = clause_shape.sub_width(1)?;
2504     // each clause on one line, trailing comma (except if suppress_comma)
2505     let span_start = where_clause.predicates[0].span().lo();
2506     // If we don't have the start of the next span, then use the end of the
2507     // predicates, but that means we miss comments.
2508     let len = where_clause.predicates.len();
2509     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2510     let span_end = span_end.unwrap_or(end_of_preds);
2511     let items = itemize_list(
2512         context.codemap,
2513         where_clause.predicates.iter(),
2514         terminator,
2515         |pred| pred.span().lo(),
2516         |pred| pred.span().hi(),
2517         |pred| pred.rewrite(context, clause_shape),
2518         span_start,
2519         span_end,
2520         false,
2521     );
2522     let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2523     let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2524         SeparatorTactic::Never
2525     } else {
2526         context.config.trailing_comma()
2527     };
2528
2529     // shape should be vertical only and only if we have `where_single_line` option enabled
2530     // and the number of items of the where clause is equal to 1
2531     let shape_tactic = if where_single_line {
2532         DefinitiveListTactic::Horizontal
2533     } else {
2534         DefinitiveListTactic::Vertical
2535     };
2536
2537     let fmt = ListFormatting {
2538         tactic: shape_tactic,
2539         separator: ",",
2540         trailing_separator: comma_tactic,
2541         separator_place: SeparatorPlace::Back,
2542         shape: clause_shape,
2543         ends_with_newline: true,
2544         preserve_newline: true,
2545         config: context.config,
2546     };
2547     let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2548
2549     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2550         String::new()
2551     } else {
2552         format!("\n{}", shape.indent.to_string(context.config))
2553     };
2554     let newline_before_where = comment_separator(&comment_before, shape);
2555     let newline_after_where = comment_separator(&comment_after, clause_shape);
2556
2557     // 6 = `where `
2558     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2559         && comment_after.is_empty() && !preds_str.contains('\n')
2560         && 6 + preds_str.len() <= shape.width || where_single_line
2561     {
2562         String::from(" ")
2563     } else {
2564         format!("\n{}", clause_shape.indent.to_string(context.config))
2565     };
2566     Some(format!(
2567         "{}{}{}where{}{}{}{}",
2568         starting_newline,
2569         comment_before,
2570         newline_before_where,
2571         newline_after_where,
2572         comment_after,
2573         clause_sep,
2574         preds_str
2575     ))
2576 }
2577
2578 fn rewrite_where_clause(
2579     context: &RewriteContext,
2580     where_clause: &ast::WhereClause,
2581     brace_style: BraceStyle,
2582     shape: Shape,
2583     density: Density,
2584     terminator: &str,
2585     span_end: Option<BytePos>,
2586     span_end_before_where: BytePos,
2587     where_clause_option: WhereClauseOption,
2588     is_args_multi_line: bool,
2589 ) -> Option<String> {
2590     if where_clause.predicates.is_empty() {
2591         return Some(String::new());
2592     }
2593
2594     if context.config.where_style() == Style::Rfc {
2595         return rewrite_where_clause_rfc_style(
2596             context,
2597             where_clause,
2598             shape,
2599             terminator,
2600             span_end,
2601             span_end_before_where,
2602             where_clause_option,
2603             is_args_multi_line,
2604         );
2605     }
2606
2607     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2608
2609     let offset = match context.config.where_pred_indent() {
2610         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2611         // 6 = "where ".len()
2612         IndentStyle::Visual => shape.indent + extra_indent + 6,
2613     };
2614     // FIXME: if where_pred_indent != Visual, then the budgets below might
2615     // be out by a char or two.
2616
2617     let budget = context.config.max_width() - offset.width();
2618     let span_start = where_clause.predicates[0].span().lo();
2619     // If we don't have the start of the next span, then use the end of the
2620     // predicates, but that means we miss comments.
2621     let len = where_clause.predicates.len();
2622     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2623     let span_end = span_end.unwrap_or(end_of_preds);
2624     let items = itemize_list(
2625         context.codemap,
2626         where_clause.predicates.iter(),
2627         terminator,
2628         |pred| pred.span().lo(),
2629         |pred| pred.span().hi(),
2630         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2631         span_start,
2632         span_end,
2633         false,
2634     );
2635     let item_vec = items.collect::<Vec<_>>();
2636     // FIXME: we don't need to collect here if the where_layout isn't
2637     // HorizontalVertical.
2638     let tactic = definitive_tactic(
2639         &item_vec,
2640         context.config.where_layout(),
2641         Separator::Comma,
2642         budget,
2643     );
2644
2645     let mut comma_tactic = context.config.trailing_comma();
2646     // Kind of a hack because we don't usually have trailing commas in where clauses.
2647     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2648         comma_tactic = SeparatorTactic::Never;
2649     }
2650
2651     let fmt = ListFormatting {
2652         tactic: tactic,
2653         separator: ",",
2654         trailing_separator: comma_tactic,
2655         separator_place: SeparatorPlace::Back,
2656         shape: Shape::legacy(budget, offset),
2657         ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2658         preserve_newline: true,
2659         config: context.config,
2660     };
2661     let preds_str = write_list(&item_vec, &fmt)?;
2662
2663     let end_length = if terminator == "{" {
2664         // If the brace is on the next line we don't need to count it otherwise it needs two
2665         // characters " {"
2666         match brace_style {
2667             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2668             BraceStyle::PreferSameLine => 2,
2669         }
2670     } else if terminator == "=" {
2671         2
2672     } else {
2673         terminator.len()
2674     };
2675     if density == Density::Tall || preds_str.contains('\n')
2676         || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2677     {
2678         Some(format!(
2679             "\n{}where {}",
2680             (shape.indent + extra_indent).to_string(context.config),
2681             preds_str
2682         ))
2683     } else {
2684         Some(format!(" where {}", preds_str))
2685     }
2686 }
2687
2688 fn missing_span_before_after_where(
2689     before_item_span_end: BytePos,
2690     where_clause: &ast::WhereClause,
2691 ) -> (Span, Span) {
2692     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2693     // 5 = `where`
2694     let pos_after_where = where_clause.span.lo() + BytePos(5);
2695     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2696     (missing_span_before, missing_span_after)
2697 }
2698
2699 fn rewrite_comments_before_after_where(
2700     context: &RewriteContext,
2701     span_before_where: Span,
2702     span_after_where: Span,
2703     shape: Shape,
2704 ) -> Option<(String, String)> {
2705     let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2706     let after_comment = rewrite_missing_comment(
2707         span_after_where,
2708         shape.block_indent(context.config.tab_spaces()),
2709         context,
2710     )?;
2711     Some((before_comment, after_comment))
2712 }
2713
2714 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2715     format!("{}{}{}", format_visibility(vis), item_name, ident)
2716 }
2717
2718 fn format_generics(
2719     context: &RewriteContext,
2720     generics: &ast::Generics,
2721     brace_style: BraceStyle,
2722     force_same_line_brace: bool,
2723     offset: Indent,
2724     span: Span,
2725     used_width: usize,
2726 ) -> Option<String> {
2727     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2728     let mut result = rewrite_generics(context, generics, shape, span)?;
2729
2730     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2731         let budget = context.budget(last_line_used_width(&result, offset.width()));
2732         let option = WhereClauseOption::snuggled(&result);
2733         // If the generics are not parameterized then generics.span.hi() == 0,
2734         // so we use span.lo(), which is the position after `struct Foo`.
2735         let span_end_before_where = if generics.is_parameterized() {
2736             generics.span.hi()
2737         } else {
2738             span.lo()
2739         };
2740         let where_clause_str = rewrite_where_clause(
2741             context,
2742             &generics.where_clause,
2743             brace_style,
2744             Shape::legacy(budget, offset.block_only()),
2745             Density::Tall,
2746             "{",
2747             Some(span.hi()),
2748             span_end_before_where,
2749             option,
2750             false,
2751         )?;
2752         result.push_str(&where_clause_str);
2753         force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2754             || (generics.where_clause.predicates.is_empty()
2755                 && trimmed_last_line_width(&result) == 1)
2756     } else {
2757         force_same_line_brace || trimmed_last_line_width(&result) == 1
2758             || brace_style != BraceStyle::AlwaysNextLine
2759     };
2760     let total_used_width = last_line_used_width(&result, used_width);
2761     let remaining_budget = context.budget(total_used_width);
2762     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2763     // and hence we take the closer into account as well for one line budget.
2764     // We assume that the closer has the same length as the opener.
2765     let overhead = if force_same_line_brace {
2766         // 3 = ` {}`
2767         3
2768     } else {
2769         // 2 = ` {`
2770         2
2771     };
2772     let forbid_same_line_brace = overhead > remaining_budget;
2773     if !forbid_same_line_brace && same_line_brace {
2774         result.push(' ');
2775     } else {
2776         result.push('\n');
2777         result.push_str(&offset.block_only().to_string(context.config));
2778     }
2779     result.push('{');
2780
2781     Some(result)
2782 }
2783
2784 impl Rewrite for ast::ForeignItem {
2785     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2786         let attrs_str = self.attrs.rewrite(context, shape)?;
2787         // Drop semicolon or it will be interpreted as comment.
2788         // FIXME: this may be a faulty span from libsyntax.
2789         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2790
2791         let item_str = match self.node {
2792             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2793                 context,
2794                 shape.indent,
2795                 self.ident,
2796                 &FnSig::new(fn_decl, generics, self.vis.clone()),
2797                 span,
2798                 false,
2799                 false,
2800             ).map(|(s, _)| format!("{};", s)),
2801             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2802                 // FIXME(#21): we're dropping potential comments in between the
2803                 // function keywords here.
2804                 let vis = format_visibility(&self.vis);
2805                 let mut_str = if is_mutable { "mut " } else { "" };
2806                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2807                 // 1 = ;
2808                 let shape = shape.sub_width(1)?;
2809                 ty.rewrite(context, shape).map(|ty_str| {
2810                     // 1 = space between prefix and type.
2811                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2812                         String::from(" ")
2813                     } else {
2814                         let nested_indent = shape.indent.block_indent(context.config);
2815                         format!("\n{}", nested_indent.to_string(context.config))
2816                     };
2817                     format!("{}{}{};", prefix, sep, ty_str)
2818                 })
2819             }
2820             ast::ForeignItemKind::Ty => {
2821                 let vis = format_visibility(&self.vis);
2822                 Some(format!("{}type {};", vis, self.ident))
2823             }
2824         }?;
2825
2826         let missing_span = if self.attrs.is_empty() {
2827             mk_sp(self.span.lo(), self.span.lo())
2828         } else {
2829             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2830         };
2831         combine_strs_with_missing_comments(
2832             context,
2833             &attrs_str,
2834             &item_str,
2835             missing_span,
2836             shape,
2837             false,
2838         )
2839     }
2840 }