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