]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Merge pull request #1889 from topecongiro/match-arm
[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(..) => {
554                 if let Some(ref expr) = field.node.disr_expr {
555                     let lhs = format!("{} =", field.node.name);
556                     rewrite_assign_rhs(&context, lhs, &**expr, shape)?
557                 } else {
558                     field.node.name.to_string()
559                 }
560             }
561         };
562
563         let attrs_extendable = attrs_str.is_empty()
564             || (context.config.same_line_attributes() && is_attributes_extendable(&attrs_str));
565         combine_strs_with_missing_comments(
566             &context,
567             &attrs_str,
568             &variant_body,
569             span,
570             shape,
571             attrs_extendable,
572         )
573     }
574 }
575
576 pub fn format_impl(
577     context: &RewriteContext,
578     item: &ast::Item,
579     offset: Indent,
580     where_span_end: Option<BytePos>,
581 ) -> Option<String> {
582     if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
583         let mut result = String::with_capacity(128);
584         let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
585         let indent_str = offset.to_string(context.config);
586         let sep = format!("\n{}", &indent_str);
587         result.push_str(&ref_and_type);
588
589         let where_budget = if result.contains('\n') {
590             context.config.max_width()
591         } else {
592             context.budget(last_line_width(&result))
593         };
594         let option = WhereClauseOption::snuggled(&ref_and_type);
595         let where_clause_str = rewrite_where_clause(
596             context,
597             &generics.where_clause,
598             context.config.brace_style(),
599             Shape::legacy(where_budget, offset.block_only()),
600             Density::Vertical,
601             "{",
602             where_span_end,
603             self_ty.span.hi(),
604             option,
605             false,
606         )?;
607
608         // If there is no where clause, we may have missing comments between the trait name and
609         // the opening brace.
610         if generics.where_clause.predicates.is_empty() {
611             if let Some(hi) = where_span_end {
612                 match recover_missing_comment_in_span(
613                     mk_sp(self_ty.span.hi(), hi),
614                     Shape::indented(offset, context.config),
615                     context,
616                     last_line_width(&result),
617                 ) {
618                     Some(ref missing_comment) if !missing_comment.is_empty() => {
619                         result.push_str(missing_comment);
620                     }
621                     _ => (),
622                 }
623             }
624         }
625
626         if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
627             result.push_str(&where_clause_str);
628             if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
629                 result.push_str(&format!("{}{{{}}}", &sep, &sep));
630             } else {
631                 result.push_str(" {}");
632             }
633             return Some(result);
634         }
635
636         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
637             result.push('\n');
638             let width = offset.block_indent + context.config.tab_spaces() - 1;
639             let where_indent = Indent::new(0, width);
640             result.push_str(&where_indent.to_string(context.config));
641         }
642         result.push_str(&where_clause_str);
643
644         match context.config.brace_style() {
645             _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
646             BraceStyle::AlwaysNextLine => result.push_str(&sep),
647             BraceStyle::PreferSameLine => result.push(' '),
648             BraceStyle::SameLineWhere => {
649                 if !where_clause_str.is_empty() {
650                     result.push_str(&sep);
651                 } else {
652                     result.push(' ');
653                 }
654             }
655         }
656
657         result.push('{');
658
659         let snippet = context.snippet(item.span);
660         let open_pos = snippet.find_uncommented("{")? + 1;
661
662         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
663             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
664             visitor.block_indent = offset.block_only().block_indent(context.config);
665             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
666
667             visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
668             for item in items {
669                 visitor.visit_impl_item(item);
670             }
671
672             visitor.format_missing(item.span.hi() - BytePos(1));
673
674             let inner_indent_str = visitor.block_indent.to_string(context.config);
675             let outer_indent_str = offset.block_only().to_string(context.config);
676
677             result.push('\n');
678             result.push_str(&inner_indent_str);
679             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
680             result.push('\n');
681             result.push_str(&outer_indent_str);
682         }
683
684         if result.ends_with('{') {
685             result.push_str(&sep);
686         }
687         result.push('}');
688
689         Some(result)
690     } else {
691         unreachable!();
692     }
693 }
694
695 fn is_impl_single_line(
696     context: &RewriteContext,
697     items: &[ImplItem],
698     result: &str,
699     where_clause_str: &str,
700     item: &ast::Item,
701 ) -> Option<bool> {
702     let snippet = context.snippet(item.span);
703     let open_pos = snippet.find_uncommented("{")? + 1;
704
705     Some(
706         context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
707             && result.len() + where_clause_str.len() <= context.config.max_width()
708             && !contains_comment(&snippet[open_pos..]),
709     )
710 }
711
712 fn format_impl_ref_and_type(
713     context: &RewriteContext,
714     item: &ast::Item,
715     offset: Indent,
716 ) -> Option<String> {
717     if let ast::ItemKind::Impl(
718         unsafety,
719         polarity,
720         defaultness,
721         ref generics,
722         ref trait_ref,
723         ref self_ty,
724         _,
725     ) = item.node
726     {
727         let mut result = String::with_capacity(128);
728
729         result.push_str(&format_visibility(&item.vis));
730         result.push_str(format_defaultness(defaultness));
731         result.push_str(format_unsafety(unsafety));
732         result.push_str("impl");
733
734         let lo = context.codemap.span_after(item.span, "impl");
735         let hi = match *trait_ref {
736             Some(ref tr) => tr.path.span.lo(),
737             None => self_ty.span.lo(),
738         };
739         let shape = generics_shape_from_config(
740             context.config,
741             Shape::indented(offset + last_line_width(&result), context.config),
742             0,
743         )?;
744         let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
745         let generics_str =
746             rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
747
748         let polarity_str = if polarity == ast::ImplPolarity::Negative {
749             "!"
750         } else {
751             ""
752         };
753
754         if let Some(ref trait_ref) = *trait_ref {
755             let result_len = result.len();
756             if let Some(trait_ref_str) = rewrite_trait_ref(
757                 context,
758                 trait_ref,
759                 offset,
760                 &generics_str,
761                 true,
762                 polarity_str,
763                 result_len,
764             ) {
765                 result.push_str(&trait_ref_str);
766             } else {
767                 let generics_str =
768                     rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
769                 result.push_str(&rewrite_trait_ref(
770                     context,
771                     trait_ref,
772                     offset,
773                     &generics_str,
774                     false,
775                     polarity_str,
776                     result_len,
777                 )?);
778             }
779         } else {
780             result.push_str(&generics_str);
781         }
782
783         // Try to put the self type in a single line.
784         // ` for`
785         let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
786         let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
787             // If there is no where clause adapt budget for type formatting to take space and curly
788             // brace into account.
789             match context.config.brace_style() {
790                 BraceStyle::AlwaysNextLine => 0,
791                 _ => 2,
792             }
793         } else {
794             0
795         };
796         let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
797         // 1 = space before the type.
798         let budget = context.budget(used_space + 1);
799         if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
800             if !self_ty_str.contains('\n') {
801                 if trait_ref.is_some() {
802                     result.push_str(" for ");
803                 } else {
804                     result.push(' ');
805                 }
806                 result.push_str(&self_ty_str);
807                 return Some(result);
808             }
809         }
810
811         // Couldn't fit the self type on a single line, put it on a new line.
812         result.push('\n');
813         // Add indentation of one additional tab.
814         let new_line_offset = offset.block_indent(context.config);
815         result.push_str(&new_line_offset.to_string(context.config));
816         if trait_ref.is_some() {
817             result.push_str("for ");
818         }
819         let budget = context.budget(last_line_width(&result));
820         let type_offset = match context.config.indent_style() {
821             IndentStyle::Visual => new_line_offset + trait_ref_overhead,
822             IndentStyle::Block => new_line_offset,
823         };
824         result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
825         Some(result)
826     } else {
827         unreachable!();
828     }
829 }
830
831 fn rewrite_trait_ref(
832     context: &RewriteContext,
833     trait_ref: &ast::TraitRef,
834     offset: Indent,
835     generics_str: &str,
836     retry: bool,
837     polarity_str: &str,
838     result_len: usize,
839 ) -> Option<String> {
840     // 1 = space between generics and trait_ref
841     let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
842     let shape = Shape::indented(offset + used_space, context.config);
843     if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
844         if !(retry && trait_ref_str.contains('\n')) {
845             return Some(format!(
846                 "{} {}{}",
847                 generics_str,
848                 polarity_str,
849                 &trait_ref_str
850             ));
851         }
852     }
853     // We could not make enough space for trait_ref, so put it on new line.
854     if !retry {
855         let offset = offset.block_indent(context.config);
856         let shape = Shape::indented(offset, context.config);
857         let trait_ref_str = trait_ref.rewrite(context, shape)?;
858         Some(format!(
859             "{}\n{}{}{}",
860             generics_str,
861             &offset.to_string(context.config),
862             polarity_str,
863             &trait_ref_str
864         ))
865     } else {
866         None
867     }
868 }
869
870 pub struct StructParts<'a> {
871     prefix: &'a str,
872     ident: ast::Ident,
873     vis: &'a ast::Visibility,
874     def: &'a ast::VariantData,
875     generics: Option<&'a ast::Generics>,
876     span: Span,
877 }
878
879 impl<'a> StructParts<'a> {
880     fn format_header(&self) -> String {
881         format_header(self.prefix, self.ident, self.vis)
882     }
883
884     fn from_variant(variant: &'a ast::Variant) -> Self {
885         StructParts {
886             prefix: "",
887             ident: variant.node.name,
888             vis: &ast::Visibility::Inherited,
889             def: &variant.node.data,
890             generics: None,
891             span: variant.span,
892         }
893     }
894
895     pub fn from_item(item: &'a ast::Item) -> Self {
896         let (prefix, def, generics) = match item.node {
897             ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
898             ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
899             _ => unreachable!(),
900         };
901         StructParts {
902             prefix: prefix,
903             ident: item.ident,
904             vis: &item.vis,
905             def: def,
906             generics: Some(generics),
907             span: item.span,
908         }
909     }
910 }
911
912 fn format_struct(
913     context: &RewriteContext,
914     struct_parts: &StructParts,
915     offset: Indent,
916     one_line_width: Option<usize>,
917 ) -> Option<String> {
918     match *struct_parts.def {
919         ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
920         ast::VariantData::Tuple(ref fields, _) => {
921             format_tuple_struct(context, struct_parts, fields, offset)
922         }
923         ast::VariantData::Struct(ref fields, _) => {
924             format_struct_struct(context, struct_parts, fields, offset, one_line_width)
925         }
926     }
927 }
928
929 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
930     if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
931         item.node
932     {
933         let mut result = String::with_capacity(128);
934         let header = format!(
935             "{}{}trait {}",
936             format_visibility(&item.vis),
937             format_unsafety(unsafety),
938             item.ident
939         );
940
941         result.push_str(&header);
942
943         let body_lo = context.codemap.span_after(item.span, "{");
944
945         let shape = Shape::indented(offset, context.config);
946         let generics_str =
947             rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
948         result.push_str(&generics_str);
949
950         // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
951         if !type_param_bounds.is_empty() {
952             let ident_hi = context.codemap.span_after(item.span, &format!("{}", item.ident));
953             let bound_hi = type_param_bounds.last().unwrap().span().hi();
954             let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
955             if contains_comment(&snippet) {
956                 return None;
957             }
958         }
959         let trait_bound_str = rewrite_trait_bounds(
960             context,
961             type_param_bounds,
962             Shape::indented(offset, context.config),
963         )?;
964         // If the trait, generics, and trait bound cannot fit on the same line,
965         // put the trait bounds on an indented new line
966         if offset.width() + last_line_width(&result) + trait_bound_str.len()
967             > context.config.comment_width()
968         {
969             result.push('\n');
970             let trait_indent = offset.block_only().block_indent(context.config);
971             result.push_str(&trait_indent.to_string(context.config));
972         }
973         result.push_str(&trait_bound_str);
974
975         let where_density =
976             if context.config.indent_style() == IndentStyle::Block && result.is_empty() {
977                 Density::Compressed
978             } else {
979                 Density::Tall
980             };
981
982         let where_budget = context.budget(last_line_width(&result));
983         let pos_before_where = if type_param_bounds.is_empty() {
984             generics.where_clause.span.lo()
985         } else {
986             type_param_bounds[type_param_bounds.len() - 1].span().hi()
987         };
988         let option = WhereClauseOption::snuggled(&generics_str);
989         let where_clause_str = rewrite_where_clause(
990             context,
991             &generics.where_clause,
992             context.config.brace_style(),
993             Shape::legacy(where_budget, offset.block_only()),
994             where_density,
995             "{",
996             None,
997             pos_before_where,
998             option,
999             false,
1000         )?;
1001         // If the where clause cannot fit on the same line,
1002         // put the where clause on a new line
1003         if !where_clause_str.contains('\n')
1004             && last_line_width(&result) + where_clause_str.len() + offset.width()
1005                 > context.config.comment_width()
1006         {
1007             result.push('\n');
1008             let width = offset.block_indent + context.config.tab_spaces() - 1;
1009             let where_indent = Indent::new(0, width);
1010             result.push_str(&where_indent.to_string(context.config));
1011         }
1012         result.push_str(&where_clause_str);
1013
1014         if generics.where_clause.predicates.is_empty() {
1015             let item_snippet = context.snippet(item.span);
1016             if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
1017                 // 1 = `{`
1018                 let comment_hi = body_lo - BytePos(1);
1019                 let comment_lo = item.span.lo() + BytePos(lo as u32);
1020                 if comment_lo < comment_hi {
1021                     match recover_missing_comment_in_span(
1022                         mk_sp(comment_lo, comment_hi),
1023                         Shape::indented(offset, context.config),
1024                         context,
1025                         last_line_width(&result),
1026                     ) {
1027                         Some(ref missing_comment) if !missing_comment.is_empty() => {
1028                             result.push_str(missing_comment);
1029                         }
1030                         _ => (),
1031                     }
1032                 }
1033             }
1034         }
1035
1036         match context.config.brace_style() {
1037             _ if last_line_contains_single_line_comment(&result) => {
1038                 result.push('\n');
1039                 result.push_str(&offset.to_string(context.config));
1040             }
1041             BraceStyle::AlwaysNextLine => {
1042                 result.push('\n');
1043                 result.push_str(&offset.to_string(context.config));
1044             }
1045             BraceStyle::PreferSameLine => result.push(' '),
1046             BraceStyle::SameLineWhere => {
1047                 if !where_clause_str.is_empty()
1048                     && (!trait_items.is_empty() || result.contains('\n'))
1049                 {
1050                     result.push('\n');
1051                     result.push_str(&offset.to_string(context.config));
1052                 } else {
1053                     result.push(' ');
1054                 }
1055             }
1056         }
1057         result.push('{');
1058
1059         let snippet = context.snippet(item.span);
1060         let open_pos = snippet.find_uncommented("{")? + 1;
1061
1062         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1063             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1064             visitor.block_indent = offset.block_only().block_indent(context.config);
1065             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1066
1067             for item in trait_items {
1068                 visitor.visit_trait_item(item);
1069             }
1070
1071             visitor.format_missing(item.span.hi() - BytePos(1));
1072
1073             let inner_indent_str = visitor.block_indent.to_string(context.config);
1074             let outer_indent_str = offset.block_only().to_string(context.config);
1075
1076             result.push('\n');
1077             result.push_str(&inner_indent_str);
1078             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1079             result.push('\n');
1080             result.push_str(&outer_indent_str);
1081         } else if result.contains('\n') {
1082             result.push('\n');
1083         }
1084
1085         result.push('}');
1086         Some(result)
1087     } else {
1088         unreachable!();
1089     }
1090 }
1091
1092 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1093     let header_str = format_header(p.prefix, p.ident, p.vis);
1094     let generics_str = if let Some(generics) = p.generics {
1095         let hi = if generics.where_clause.predicates.is_empty() {
1096             generics.span.hi()
1097         } else {
1098             generics.where_clause.span.hi()
1099         };
1100         format_generics(
1101             context,
1102             generics,
1103             context.config.brace_style(),
1104             BracePos::None,
1105             offset,
1106             mk_sp(generics.span.lo(), hi),
1107             last_line_width(&header_str),
1108         )?
1109     } else {
1110         String::new()
1111     };
1112     Some(format!("{}{};", header_str, generics_str))
1113 }
1114
1115 pub fn format_struct_struct(
1116     context: &RewriteContext,
1117     struct_parts: &StructParts,
1118     fields: &[ast::StructField],
1119     offset: Indent,
1120     one_line_width: Option<usize>,
1121 ) -> Option<String> {
1122     let mut result = String::with_capacity(1024);
1123     let span = struct_parts.span;
1124
1125     let header_str = struct_parts.format_header();
1126     result.push_str(&header_str);
1127
1128     let header_hi = span.lo() + BytePos(header_str.len() as u32);
1129     let body_lo = context.codemap.span_after(span, "{");
1130
1131     let generics_str = match struct_parts.generics {
1132         Some(g) => format_generics(
1133             context,
1134             g,
1135             context.config.brace_style(),
1136             if fields.is_empty() {
1137                 BracePos::ForceSameLine
1138             } else {
1139                 BracePos::Auto
1140             },
1141             offset,
1142             mk_sp(header_hi, body_lo),
1143             last_line_width(&result),
1144         )?,
1145         None => {
1146             // 3 = ` {}`, 2 = ` {`.
1147             let overhead = if fields.is_empty() { 3 } else { 2 };
1148             if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1149                 || context.config.max_width() < overhead + result.len()
1150             {
1151                 format!("\n{}{{", offset.block_only().to_string(context.config))
1152             } else {
1153                 " {".to_owned()
1154             }
1155         }
1156     };
1157     // 1 = `}`
1158     let overhead = if fields.is_empty() { 1 } else { 0 };
1159     let total_width = result.len() + generics_str.len() + overhead;
1160     if !generics_str.is_empty() && !generics_str.contains('\n')
1161         && total_width > context.config.max_width()
1162     {
1163         result.push('\n');
1164         result.push_str(&offset.to_string(context.config));
1165         result.push_str(generics_str.trim_left());
1166     } else {
1167         result.push_str(&generics_str);
1168     }
1169
1170     if fields.is_empty() {
1171         let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1172         if snippet.trim().is_empty() {
1173             // `struct S {}`
1174         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1175             // fix indent
1176             result.push_str(snippet.trim_right());
1177             result.push('\n');
1178             result.push_str(&offset.to_string(context.config));
1179         } else {
1180             result.push_str(&snippet);
1181         }
1182         result.push('}');
1183         return Some(result);
1184     }
1185
1186     // 3 = ` ` and ` }`
1187     let one_line_budget = context.budget(result.len() + 3 + offset.width());
1188     let one_line_budget =
1189         one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1190
1191     let items_str = rewrite_with_alignment(
1192         fields,
1193         context,
1194         Shape::indented(offset, context.config).sub_width(1)?,
1195         mk_sp(body_lo, span.hi()),
1196         one_line_budget,
1197     )?;
1198
1199     if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1200         Some(format!("{} {} }}", result, items_str))
1201     } else {
1202         Some(format!(
1203             "{}\n{}{}\n{}}}",
1204             result,
1205             offset
1206                 .block_indent(context.config)
1207                 .to_string(context.config),
1208             items_str,
1209             offset.to_string(context.config)
1210         ))
1211     }
1212 }
1213
1214 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1215 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1216 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1217 fn get_bytepos_after_visibility(
1218     context: &RewriteContext,
1219     vis: &ast::Visibility,
1220     default_span: Span,
1221     terminator: &str,
1222 ) -> BytePos {
1223     match *vis {
1224         ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1225             .codemap
1226             .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1227         ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1228         ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1229         _ => default_span.lo(),
1230     }
1231 }
1232
1233 fn format_tuple_struct(
1234     context: &RewriteContext,
1235     struct_parts: &StructParts,
1236     fields: &[ast::StructField],
1237     offset: Indent,
1238 ) -> Option<String> {
1239     let mut result = String::with_capacity(1024);
1240     let span = struct_parts.span;
1241
1242     let header_str = struct_parts.format_header();
1243     result.push_str(&header_str);
1244
1245     let body_lo = if fields.is_empty() {
1246         let lo = get_bytepos_after_visibility(context, struct_parts.vis, span, ")");
1247         context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1248     } else {
1249         fields[0].span.lo()
1250     };
1251     let body_hi = if fields.is_empty() {
1252         context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1253     } else {
1254         // This is a dirty hack to work around a missing `)` from the span of the last field.
1255         let last_arg_span = fields[fields.len() - 1].span;
1256         if context.snippet(last_arg_span).ends_with(')') {
1257             last_arg_span.hi()
1258         } else {
1259             context
1260                 .codemap
1261                 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1262         }
1263     };
1264
1265     let where_clause_str = match struct_parts.generics {
1266         Some(generics) => {
1267             let budget = context.budget(last_line_width(&header_str));
1268             let shape = Shape::legacy(budget, offset);
1269             let g_span = mk_sp(span.lo(), body_lo);
1270             let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1271             result.push_str(&generics_str);
1272
1273             let where_budget = context.budget(last_line_width(&result));
1274             let option = WhereClauseOption::new(true, false);
1275             rewrite_where_clause(
1276                 context,
1277                 &generics.where_clause,
1278                 context.config.brace_style(),
1279                 Shape::legacy(where_budget, offset.block_only()),
1280                 Density::Compressed,
1281                 ";",
1282                 None,
1283                 body_hi,
1284                 option,
1285                 false,
1286             )?
1287         }
1288         None => "".to_owned(),
1289     };
1290
1291     if fields.is_empty() {
1292         // 3 = `();`
1293         let used_width = last_line_used_width(&result, offset.width()) + 3;
1294         if used_width > context.config.max_width() {
1295             result.push('\n');
1296             result.push_str(&offset
1297                 .block_indent(context.config)
1298                 .to_string(context.config))
1299         }
1300         result.push('(');
1301         let snippet = context.snippet(mk_sp(
1302             body_lo,
1303             context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1304         ));
1305         if snippet.is_empty() {
1306             // `struct S ()`
1307         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1308             result.push_str(snippet.trim_right());
1309             result.push('\n');
1310             result.push_str(&offset.to_string(context.config));
1311         } else {
1312             result.push_str(&snippet);
1313         }
1314         result.push(')');
1315     } else {
1316         let shape = Shape::indented(offset, context.config).sub_width(1)?;
1317         let fields = &fields.iter().collect::<Vec<_>>()[..];
1318         let one_line_width = context.config.width_heuristics().fn_call_width;
1319         result = rewrite_call_inner(context, &result, fields, span, shape, one_line_width, false)?;
1320     }
1321
1322     if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1323         && (result.contains('\n')
1324             || offset.block_indent + result.len() + where_clause_str.len() + 1
1325                 > context.config.max_width())
1326     {
1327         // We need to put the where clause on a new line, but we didn't
1328         // know that earlier, so the where clause will not be indented properly.
1329         result.push('\n');
1330         result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1331             .to_string(context.config));
1332     }
1333     result.push_str(&where_clause_str);
1334
1335     Some(result)
1336 }
1337
1338 pub fn rewrite_type_alias(
1339     context: &RewriteContext,
1340     indent: Indent,
1341     ident: ast::Ident,
1342     ty: &ast::Ty,
1343     generics: &ast::Generics,
1344     vis: &ast::Visibility,
1345     span: Span,
1346 ) -> Option<String> {
1347     let mut result = String::with_capacity(128);
1348
1349     result.push_str(&format_visibility(vis));
1350     result.push_str("type ");
1351     result.push_str(&ident.to_string());
1352
1353     // 2 = `= `
1354     let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1355     let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1356     let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1357     result.push_str(&generics_str);
1358
1359     let where_budget = context.budget(last_line_width(&result));
1360     let option = WhereClauseOption::snuggled(&result);
1361     let where_clause_str = rewrite_where_clause(
1362         context,
1363         &generics.where_clause,
1364         context.config.brace_style(),
1365         Shape::legacy(where_budget, indent),
1366         Density::Vertical,
1367         "=",
1368         Some(span.hi()),
1369         generics.span.hi(),
1370         option,
1371         false,
1372     )?;
1373     result.push_str(&where_clause_str);
1374     if where_clause_str.is_empty() {
1375         result.push_str(" = ");
1376     } else {
1377         result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1378     }
1379
1380     let line_width = last_line_width(&result);
1381     // This checked_sub may fail as the extra space after '=' is not taken into account
1382     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1383     let budget = context.budget(indent.width() + line_width + ";".len());
1384     let type_indent = indent + line_width;
1385     // Try to fit the type on the same line
1386     let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1387         .or_else(|| {
1388             // The line was too short, try to put the type on the next line
1389
1390             // Remove the space after '='
1391             result.pop();
1392             let type_indent = indent.block_indent(context.config);
1393             result.push('\n');
1394             result.push_str(&type_indent.to_string(context.config));
1395             let budget = context.budget(type_indent.width() + ";".len());
1396             ty.rewrite(context, Shape::legacy(budget, type_indent))
1397         })?;
1398     result.push_str(&ty_str);
1399     result.push_str(";");
1400     Some(result)
1401 }
1402
1403 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1404     (
1405         if config.space_before_colon() { " " } else { "" },
1406         if config.space_after_colon() { " " } else { "" },
1407     )
1408 }
1409
1410 pub fn rewrite_struct_field_prefix(
1411     context: &RewriteContext,
1412     field: &ast::StructField,
1413 ) -> Option<String> {
1414     let vis = format_visibility(&field.vis);
1415     let type_annotation_spacing = type_annotation_spacing(context.config);
1416     Some(match field.ident {
1417         Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1418         None => format!("{}", vis),
1419     })
1420 }
1421
1422 impl Rewrite for ast::StructField {
1423     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1424         rewrite_struct_field(context, self, shape, 0)
1425     }
1426 }
1427
1428 pub fn rewrite_struct_field(
1429     context: &RewriteContext,
1430     field: &ast::StructField,
1431     shape: Shape,
1432     lhs_max_width: usize,
1433 ) -> Option<String> {
1434     if contains_skip(&field.attrs) {
1435         return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1436     }
1437
1438     let type_annotation_spacing = type_annotation_spacing(context.config);
1439     let prefix = rewrite_struct_field_prefix(context, field)?;
1440
1441     let attrs_str = field.attrs.rewrite(context, shape)?;
1442     let attrs_extendable = attrs_str.is_empty()
1443         || (context.config.same_line_attributes() && is_attributes_extendable(&attrs_str));
1444     let missing_span = if field.attrs.is_empty() {
1445         mk_sp(field.span.lo(), field.span.lo())
1446     } else {
1447         mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1448     };
1449     let mut spacing = String::from(if field.ident.is_some() {
1450         type_annotation_spacing.1
1451     } else {
1452         ""
1453     });
1454     // Try to put everything on a single line.
1455     let attr_prefix = combine_strs_with_missing_comments(
1456         context,
1457         &attrs_str,
1458         &prefix,
1459         missing_span,
1460         shape,
1461         attrs_extendable,
1462     )?;
1463     let overhead = last_line_width(&attr_prefix);
1464     let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1465     for _ in 0..lhs_offset {
1466         spacing.push(' ');
1467     }
1468     // In this extreme case we will be missing a space betweeen an attribute and a field.
1469     if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1470         spacing.push(' ');
1471     }
1472     let ty_shape = shape.offset_left(overhead + spacing.len())?;
1473     let mut orig_ty = field.ty.rewrite(context, ty_shape);
1474     if let Some(ref ty) = orig_ty {
1475         if !ty.contains('\n') {
1476             return Some(attr_prefix + &spacing + ty);
1477         }
1478     }
1479
1480     // We must use multiline. We are going to put attributes and a field on different lines.
1481     // 1 = " "
1482     let rhs_shape = shape.offset_left(last_line_width(&prefix) + 1)?;
1483     orig_ty = field.ty.rewrite(context, rhs_shape);
1484     let field_str = if prefix.is_empty() {
1485         orig_ty?
1486     } else {
1487         prefix + &choose_rhs(context, &*field.ty, rhs_shape, orig_ty)?
1488     };
1489     combine_strs_with_missing_comments(context, &attrs_str, &field_str, missing_span, shape, false)
1490 }
1491
1492 pub struct StaticParts<'a> {
1493     prefix: &'a str,
1494     vis: &'a ast::Visibility,
1495     ident: ast::Ident,
1496     ty: &'a ast::Ty,
1497     mutability: ast::Mutability,
1498     expr_opt: Option<&'a ptr::P<ast::Expr>>,
1499     span: Span,
1500 }
1501
1502 impl<'a> StaticParts<'a> {
1503     pub fn from_item(item: &'a ast::Item) -> Self {
1504         let (prefix, ty, mutability, expr) = match item.node {
1505             ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1506             ast::ItemKind::Const(ref ty, ref expr) => {
1507                 ("const", ty, ast::Mutability::Immutable, expr)
1508             }
1509             _ => unreachable!(),
1510         };
1511         StaticParts {
1512             prefix: prefix,
1513             vis: &item.vis,
1514             ident: item.ident,
1515             ty: ty,
1516             mutability: mutability,
1517             expr_opt: Some(expr),
1518             span: item.span,
1519         }
1520     }
1521
1522     pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1523         let (ty, expr_opt) = match ti.node {
1524             ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1525             _ => unreachable!(),
1526         };
1527         StaticParts {
1528             prefix: "const",
1529             vis: &ast::Visibility::Inherited,
1530             ident: ti.ident,
1531             ty: ty,
1532             mutability: ast::Mutability::Immutable,
1533             expr_opt: expr_opt.as_ref(),
1534             span: ti.span,
1535         }
1536     }
1537
1538     pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1539         let (ty, expr) = match ii.node {
1540             ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1541             _ => unreachable!(),
1542         };
1543         StaticParts {
1544             prefix: "const",
1545             vis: &ii.vis,
1546             ident: ii.ident,
1547             ty: ty,
1548             mutability: ast::Mutability::Immutable,
1549             expr_opt: Some(expr),
1550             span: ii.span,
1551         }
1552     }
1553 }
1554
1555 fn rewrite_static(
1556     context: &RewriteContext,
1557     static_parts: &StaticParts,
1558     offset: Indent,
1559 ) -> Option<String> {
1560     let colon = colon_spaces(
1561         context.config.space_before_colon(),
1562         context.config.space_after_colon(),
1563     );
1564     let prefix = format!(
1565         "{}{} {}{}{}",
1566         format_visibility(static_parts.vis),
1567         static_parts.prefix,
1568         format_mutability(static_parts.mutability),
1569         static_parts.ident,
1570         colon,
1571     );
1572     // 2 = " =".len()
1573     let ty_shape =
1574         Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1575     let ty_str = static_parts.ty.rewrite(context, ty_shape)?;
1576
1577     if let Some(expr) = static_parts.expr_opt {
1578         let lhs = format!("{}{} =", prefix, ty_str);
1579         // 1 = ;
1580         let remaining_width = context.budget(offset.block_indent + 1);
1581         rewrite_assign_rhs(
1582             context,
1583             lhs,
1584             &**expr,
1585             Shape::legacy(remaining_width, offset.block_only()),
1586         ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1587             .map(|s| if s.ends_with(';') { s } else { s + ";" })
1588     } else {
1589         Some(format!("{}{};", prefix, ty_str))
1590     }
1591 }
1592
1593 pub fn rewrite_associated_type(
1594     ident: ast::Ident,
1595     ty_opt: Option<&ptr::P<ast::Ty>>,
1596     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1597     context: &RewriteContext,
1598     indent: Indent,
1599 ) -> Option<String> {
1600     let prefix = format!("type {}", ident);
1601
1602     let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1603         // 2 = ": ".len()
1604         let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1605         let bound_str = bounds
1606             .iter()
1607             .map(|ty_bound| ty_bound.rewrite(context, shape))
1608             .collect::<Option<Vec<_>>>()?;
1609         if !bounds.is_empty() {
1610             format!(": {}", join_bounds(context, shape, &bound_str))
1611         } else {
1612             String::new()
1613         }
1614     } else {
1615         String::new()
1616     };
1617
1618     if let Some(ty) = ty_opt {
1619         // 1 = `;`
1620         let shape = Shape::indented(indent, context.config).sub_width(1)?;
1621         let lhs = format!("{}{} =", prefix, type_bounds_str);
1622         rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1623     } else {
1624         Some(format!("{}{};", prefix, type_bounds_str))
1625     }
1626 }
1627
1628 pub fn rewrite_associated_impl_type(
1629     ident: ast::Ident,
1630     defaultness: ast::Defaultness,
1631     ty_opt: Option<&ptr::P<ast::Ty>>,
1632     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1633     context: &RewriteContext,
1634     indent: Indent,
1635 ) -> Option<String> {
1636     let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1637
1638     match defaultness {
1639         ast::Defaultness::Default => Some(format!("default {}", result)),
1640         _ => Some(result),
1641     }
1642 }
1643
1644 impl Rewrite for ast::FunctionRetTy {
1645     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1646         match *self {
1647             ast::FunctionRetTy::Default(_) => Some(String::new()),
1648             ast::FunctionRetTy::Ty(ref ty) => {
1649                 let inner_width = shape.width.checked_sub(3)?;
1650                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1651                     .map(|r| format!("-> {}", r))
1652             }
1653         }
1654     }
1655 }
1656
1657 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1658     match ty.node {
1659         ast::TyKind::Infer => {
1660             let original = context.snippet(ty.span);
1661             original != "_"
1662         }
1663         _ => false,
1664     }
1665 }
1666
1667 impl Rewrite for ast::Arg {
1668     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1669         if is_named_arg(self) {
1670             let mut result = self.pat
1671                 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1672
1673             if !is_empty_infer(context, &*self.ty) {
1674                 if context.config.space_before_colon() {
1675                     result.push_str(" ");
1676                 }
1677                 result.push_str(":");
1678                 if context.config.space_after_colon() {
1679                     result.push_str(" ");
1680                 }
1681                 let overhead = last_line_width(&result);
1682                 let max_width = shape.width.checked_sub(overhead)?;
1683                 let ty_str = self.ty
1684                     .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1685                 result.push_str(&ty_str);
1686             }
1687
1688             Some(result)
1689         } else {
1690             self.ty.rewrite(context, shape)
1691         }
1692     }
1693 }
1694
1695 fn rewrite_explicit_self(
1696     explicit_self: &ast::ExplicitSelf,
1697     args: &[ast::Arg],
1698     context: &RewriteContext,
1699 ) -> Option<String> {
1700     match explicit_self.node {
1701         ast::SelfKind::Region(lt, m) => {
1702             let mut_str = format_mutability(m);
1703             match lt {
1704                 Some(ref l) => {
1705                     let lifetime_str = l.rewrite(
1706                         context,
1707                         Shape::legacy(context.config.max_width(), Indent::empty()),
1708                     )?;
1709                     Some(format!("&{} {}self", lifetime_str, mut_str))
1710                 }
1711                 None => Some(format!("&{}self", mut_str)),
1712             }
1713         }
1714         ast::SelfKind::Explicit(ref ty, _) => {
1715             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1716
1717             let mutability = explicit_self_mutability(&args[0]);
1718             let type_str = ty.rewrite(
1719                 context,
1720                 Shape::legacy(context.config.max_width(), Indent::empty()),
1721             )?;
1722
1723             Some(format!(
1724                 "{}self: {}",
1725                 format_mutability(mutability),
1726                 type_str
1727             ))
1728         }
1729         ast::SelfKind::Value(_) => {
1730             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1731
1732             let mutability = explicit_self_mutability(&args[0]);
1733
1734             Some(format!("{}self", format_mutability(mutability)))
1735         }
1736     }
1737 }
1738
1739 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1740 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1741 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1742     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1743         mutability
1744     } else {
1745         unreachable!()
1746     }
1747 }
1748
1749 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1750     if is_named_arg(arg) {
1751         arg.pat.span.lo()
1752     } else {
1753         arg.ty.span.lo()
1754     }
1755 }
1756
1757 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1758     match arg.ty.node {
1759         ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1760         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1761         _ => arg.ty.span.hi(),
1762     }
1763 }
1764
1765 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1766     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1767         ident.node != symbol::keywords::Invalid.ident()
1768     } else {
1769         true
1770     }
1771 }
1772
1773 // Return type is (result, force_new_line_for_brace)
1774 fn rewrite_fn_base(
1775     context: &RewriteContext,
1776     indent: Indent,
1777     ident: ast::Ident,
1778     fn_sig: &FnSig,
1779     span: Span,
1780     newline_brace: bool,
1781     has_body: bool,
1782 ) -> Option<(String, bool)> {
1783     let mut force_new_line_for_brace = false;
1784
1785     let where_clause = &fn_sig.generics.where_clause;
1786
1787     let mut result = String::with_capacity(1024);
1788     result.push_str(&fn_sig.to_str(context));
1789
1790     // fn foo
1791     result.push_str("fn ");
1792     result.push_str(&ident.to_string());
1793
1794     // Generics.
1795     let overhead = if has_body && !newline_brace {
1796         // 4 = `() {`
1797         4
1798     } else {
1799         // 2 = `()`
1800         2
1801     };
1802     let used_width = last_line_used_width(&result, indent.width());
1803     let one_line_budget = context.budget(used_width + overhead);
1804     let shape = Shape {
1805         width: one_line_budget,
1806         indent: indent,
1807         offset: used_width,
1808     };
1809     let fd = fn_sig.decl;
1810     let g_span = mk_sp(span.lo(), fd.output.span().lo());
1811     let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1812     result.push_str(&generics_str);
1813
1814     let snuggle_angle_bracket = generics_str
1815         .lines()
1816         .last()
1817         .map_or(false, |l| l.trim_left().len() == 1);
1818
1819     // Note that the width and indent don't really matter, we'll re-layout the
1820     // return type later anyway.
1821     let ret_str = fd.output
1822         .rewrite(context, Shape::indented(indent, context.config))?;
1823
1824     let multi_line_ret_str = ret_str.contains('\n');
1825     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1826
1827     // Args.
1828     let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1829         context,
1830         &result,
1831         indent,
1832         ret_str_len,
1833         newline_brace,
1834         has_body,
1835         multi_line_ret_str,
1836     )?;
1837
1838     debug!(
1839         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1840         one_line_budget,
1841         multi_line_budget,
1842         arg_indent
1843     );
1844
1845     // Check if vertical layout was forced.
1846     if one_line_budget == 0 {
1847         if snuggle_angle_bracket {
1848             result.push('(');
1849         } else {
1850             result.push_str("(");
1851             if context.config.indent_style() == IndentStyle::Visual {
1852                 result.push('\n');
1853                 result.push_str(&arg_indent.to_string(context.config));
1854             }
1855         }
1856     } else {
1857         result.push('(');
1858     }
1859     if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1860         && result.ends_with('(')
1861     {
1862         result.push(' ')
1863     }
1864
1865     // Skip `pub(crate)`.
1866     let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1867     // A conservative estimation, to goal is to be over all parens in generics
1868     let args_start = fn_sig
1869         .generics
1870         .ty_params
1871         .last()
1872         .map_or(lo_after_visibility, |tp| end_typaram(tp));
1873     let args_end = if fd.inputs.is_empty() {
1874         context
1875             .codemap
1876             .span_after(mk_sp(args_start, span.hi()), ")")
1877     } else {
1878         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1879         context.codemap.span_after(last_span, ")")
1880     };
1881     let args_span = mk_sp(
1882         context
1883             .codemap
1884             .span_after(mk_sp(args_start, span.hi()), "("),
1885         args_end,
1886     );
1887     let arg_str = rewrite_args(
1888         context,
1889         &fd.inputs,
1890         fd.get_self().as_ref(),
1891         one_line_budget,
1892         multi_line_budget,
1893         indent,
1894         arg_indent,
1895         args_span,
1896         fd.variadic,
1897         generics_str.contains('\n'),
1898     )?;
1899
1900     let put_args_in_block = match context.config.indent_style() {
1901         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1902         _ => false,
1903     } && !fd.inputs.is_empty();
1904
1905     let mut args_last_line_contains_comment = false;
1906     if put_args_in_block {
1907         arg_indent = indent.block_indent(context.config);
1908         result.push('\n');
1909         result.push_str(&arg_indent.to_string(context.config));
1910         result.push_str(&arg_str);
1911         result.push('\n');
1912         result.push_str(&indent.to_string(context.config));
1913         result.push(')');
1914     } else {
1915         result.push_str(&arg_str);
1916         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1917         // Put the closing brace on the next line if it overflows the max width.
1918         // 1 = `)`
1919         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1920             result.push('\n');
1921         }
1922         if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1923             result.push(' ')
1924         }
1925         // If the last line of args contains comment, we cannot put the closing paren
1926         // on the same line.
1927         if arg_str
1928             .lines()
1929             .last()
1930             .map_or(false, |last_line| last_line.contains("//"))
1931         {
1932             args_last_line_contains_comment = true;
1933             result.push('\n');
1934             result.push_str(&arg_indent.to_string(context.config));
1935         }
1936         result.push(')');
1937     }
1938
1939     // Return type.
1940     if let ast::FunctionRetTy::Ty(..) = fd.output {
1941         let ret_should_indent = match context.config.indent_style() {
1942             // If our args are block layout then we surely must have space.
1943             IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1944             _ if args_last_line_contains_comment => false,
1945             _ if result.contains('\n') || multi_line_ret_str => true,
1946             _ => {
1947                 // If the return type would push over the max width, then put the return type on
1948                 // a new line. With the +1 for the signature length an additional space between
1949                 // the closing parenthesis of the argument and the arrow '->' is considered.
1950                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1951
1952                 // If there is no where clause, take into account the space after the return type
1953                 // and the brace.
1954                 if where_clause.predicates.is_empty() {
1955                     sig_length += 2;
1956                 }
1957
1958                 sig_length > context.config.max_width()
1959             }
1960         };
1961         let ret_indent = if ret_should_indent {
1962             let indent = if arg_str.is_empty() {
1963                 // Aligning with non-existent args looks silly.
1964                 force_new_line_for_brace = true;
1965                 indent + 4
1966             } else {
1967                 // FIXME: we might want to check that using the arg indent
1968                 // doesn't blow our budget, and if it does, then fallback to
1969                 // the where clause indent.
1970                 arg_indent
1971             };
1972
1973             result.push('\n');
1974             result.push_str(&indent.to_string(context.config));
1975             indent
1976         } else {
1977             result.push(' ');
1978             Indent::new(indent.block_indent, last_line_width(&result))
1979         };
1980
1981         if multi_line_ret_str || ret_should_indent {
1982             // Now that we know the proper indent and width, we need to
1983             // re-layout the return type.
1984             let ret_str = fd.output
1985                 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1986             result.push_str(&ret_str);
1987         } else {
1988             result.push_str(&ret_str);
1989         }
1990
1991         // Comment between return type and the end of the decl.
1992         let snippet_lo = fd.output.span().hi();
1993         if where_clause.predicates.is_empty() {
1994             let snippet_hi = span.hi();
1995             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1996             // Try to preserve the layout of the original snippet.
1997             let original_starts_with_newline = snippet
1998                 .find(|c| c != ' ')
1999                 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2000             let original_ends_with_newline = snippet
2001                 .rfind(|c| c != ' ')
2002                 .map_or(false, |i| snippet[i..].ends_with('\n'));
2003             let snippet = snippet.trim();
2004             if !snippet.is_empty() {
2005                 result.push(if original_starts_with_newline {
2006                     '\n'
2007                 } else {
2008                     ' '
2009                 });
2010                 result.push_str(snippet);
2011                 if original_ends_with_newline {
2012                     force_new_line_for_brace = true;
2013                 }
2014             }
2015         }
2016     }
2017
2018     let pos_before_where = match fd.output {
2019         ast::FunctionRetTy::Default(..) => args_span.hi(),
2020         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2021     };
2022
2023     let is_args_multi_lined = arg_str.contains('\n');
2024
2025     let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2026     let where_clause_str = rewrite_where_clause(
2027         context,
2028         where_clause,
2029         context.config.brace_style(),
2030         Shape::indented(indent, context.config),
2031         Density::Tall,
2032         "{",
2033         Some(span.hi()),
2034         pos_before_where,
2035         option,
2036         is_args_multi_lined,
2037     )?;
2038     // If there are neither where clause nor return type, we may be missing comments between
2039     // args and `{`.
2040     if where_clause_str.is_empty() {
2041         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2042             match recover_missing_comment_in_span(
2043                 mk_sp(args_span.hi(), ret_span.hi()),
2044                 shape,
2045                 context,
2046                 last_line_width(&result),
2047             ) {
2048                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2049                     result.push_str(missing_comment);
2050                     force_new_line_for_brace = true;
2051                 }
2052                 _ => (),
2053             }
2054         }
2055     }
2056
2057     result.push_str(&where_clause_str);
2058
2059     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2060     force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2061     Some((result, force_new_line_for_brace))
2062 }
2063
2064 #[derive(Copy, Clone)]
2065 struct WhereClauseOption {
2066     suppress_comma: bool, // Force no trailing comma
2067     snuggle: bool,        // Do not insert newline before `where`
2068     compress_where: bool, // Try single line where clause instead of vertical layout
2069 }
2070
2071 impl WhereClauseOption {
2072     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2073         WhereClauseOption {
2074             suppress_comma: suppress_comma,
2075             snuggle: snuggle,
2076             compress_where: false,
2077         }
2078     }
2079
2080     pub fn snuggled(current: &str) -> WhereClauseOption {
2081         WhereClauseOption {
2082             suppress_comma: false,
2083             snuggle: trimmed_last_line_width(current) == 1,
2084             compress_where: false,
2085         }
2086     }
2087 }
2088
2089 fn rewrite_args(
2090     context: &RewriteContext,
2091     args: &[ast::Arg],
2092     explicit_self: Option<&ast::ExplicitSelf>,
2093     one_line_budget: usize,
2094     multi_line_budget: usize,
2095     indent: Indent,
2096     arg_indent: Indent,
2097     span: Span,
2098     variadic: bool,
2099     generics_str_contains_newline: bool,
2100 ) -> Option<String> {
2101     let mut arg_item_strs = args.iter()
2102         .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2103         .collect::<Option<Vec<_>>>()?;
2104
2105     // Account for sugary self.
2106     // FIXME: the comment for the self argument is dropped. This is blocked
2107     // on rust issue #27522.
2108     let min_args = explicit_self
2109         .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2110         .map_or(1, |self_str| {
2111             arg_item_strs[0] = self_str;
2112             2
2113         });
2114
2115     // Comments between args.
2116     let mut arg_items = Vec::new();
2117     if min_args == 2 {
2118         arg_items.push(ListItem::from_str(""));
2119     }
2120
2121     // FIXME(#21): if there are no args, there might still be a comment, but
2122     // without spans for the comment or parens, there is no chance of
2123     // getting it right. You also don't get to put a comment on self, unless
2124     // it is explicit.
2125     if args.len() >= min_args || variadic {
2126         let comment_span_start = if min_args == 2 {
2127             let second_arg_start = if arg_has_pattern(&args[1]) {
2128                 args[1].pat.span.lo()
2129             } else {
2130                 args[1].ty.span.lo()
2131             };
2132             let reduced_span = mk_sp(span.lo(), second_arg_start);
2133
2134             context.codemap.span_after_last(reduced_span, ",")
2135         } else {
2136             span.lo()
2137         };
2138
2139         enum ArgumentKind<'a> {
2140             Regular(&'a ast::Arg),
2141             Variadic(BytePos),
2142         }
2143
2144         let variadic_arg = if variadic {
2145             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2146             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2147             Some(ArgumentKind::Variadic(variadic_start))
2148         } else {
2149             None
2150         };
2151
2152         let more_items = itemize_list(
2153             context.codemap,
2154             args[min_args - 1..]
2155                 .iter()
2156                 .map(ArgumentKind::Regular)
2157                 .chain(variadic_arg),
2158             ")",
2159             ",",
2160             |arg| match *arg {
2161                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2162                 ArgumentKind::Variadic(start) => start,
2163             },
2164             |arg| match *arg {
2165                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2166                 ArgumentKind::Variadic(start) => start + BytePos(3),
2167             },
2168             |arg| match *arg {
2169                 ArgumentKind::Regular(..) => None,
2170                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2171             },
2172             comment_span_start,
2173             span.hi(),
2174             false,
2175         );
2176
2177         arg_items.extend(more_items);
2178     }
2179
2180     let fits_in_one_line = !generics_str_contains_newline
2181         && (arg_items.is_empty()
2182             || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2183
2184     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2185         item.item = Some(arg);
2186     }
2187
2188     let last_line_ends_with_comment = arg_items
2189         .iter()
2190         .last()
2191         .and_then(|item| item.post_comment.as_ref())
2192         .map_or(false, |s| s.trim().starts_with("//"));
2193
2194     let (indent, trailing_comma) = match context.config.indent_style() {
2195         IndentStyle::Block if fits_in_one_line => {
2196             (indent.block_indent(context.config), SeparatorTactic::Never)
2197         }
2198         IndentStyle::Block => (
2199             indent.block_indent(context.config),
2200             context.config.trailing_comma(),
2201         ),
2202         IndentStyle::Visual if last_line_ends_with_comment => {
2203             (arg_indent, context.config.trailing_comma())
2204         }
2205         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2206     };
2207
2208     let tactic = definitive_tactic(
2209         &arg_items,
2210         context.config.fn_args_density().to_list_tactic(),
2211         Separator::Comma,
2212         one_line_budget,
2213     );
2214     let budget = match tactic {
2215         DefinitiveListTactic::Horizontal => one_line_budget,
2216         _ => multi_line_budget,
2217     };
2218
2219     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2220
2221     let fmt = ListFormatting {
2222         tactic: tactic,
2223         separator: ",",
2224         trailing_separator: if variadic {
2225             SeparatorTactic::Never
2226         } else {
2227             trailing_comma
2228         },
2229         separator_place: SeparatorPlace::Back,
2230         shape: Shape::legacy(budget, indent),
2231         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2232         preserve_newline: true,
2233         config: context.config,
2234     };
2235
2236     write_list(&arg_items, &fmt)
2237 }
2238
2239 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2240     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2241         ident.node != symbol::keywords::Invalid.ident()
2242     } else {
2243         true
2244     }
2245 }
2246
2247 fn compute_budgets_for_args(
2248     context: &RewriteContext,
2249     result: &str,
2250     indent: Indent,
2251     ret_str_len: usize,
2252     newline_brace: bool,
2253     has_braces: bool,
2254     force_vertical_layout: bool,
2255 ) -> Option<((usize, usize, Indent))> {
2256     debug!(
2257         "compute_budgets_for_args {} {:?}, {}, {}",
2258         result.len(),
2259         indent,
2260         ret_str_len,
2261         newline_brace
2262     );
2263     // Try keeping everything on the same line.
2264     if !result.contains('\n') && !force_vertical_layout {
2265         // 2 = `()`, 3 = `() `, space is before ret_string.
2266         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2267         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2268         if has_braces {
2269             if !newline_brace {
2270                 // 2 = `{}`
2271                 used_space += 2;
2272             }
2273         } else {
2274             // 1 = `;`
2275             used_space += 1;
2276         }
2277         let one_line_budget = context.budget(used_space);
2278
2279         if one_line_budget > 0 {
2280             // 4 = "() {".len()
2281             let (indent, multi_line_budget) = match context.config.indent_style() {
2282                 IndentStyle::Block => {
2283                     let indent = indent.block_indent(context.config);
2284                     (indent, context.budget(indent.width() + 1))
2285                 }
2286                 IndentStyle::Visual => {
2287                     let indent = indent + result.len() + 1;
2288                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2289                     (indent, context.budget(multi_line_overhead))
2290                 }
2291             };
2292
2293             return Some((one_line_budget, multi_line_budget, indent));
2294         }
2295     }
2296
2297     // Didn't work. we must force vertical layout and put args on a newline.
2298     let new_indent = indent.block_indent(context.config);
2299     let used_space = match context.config.indent_style() {
2300         // 1 = `,`
2301         IndentStyle::Block => new_indent.width() + 1,
2302         // Account for `)` and possibly ` {`.
2303         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2304     };
2305     Some((0, context.budget(used_space), new_indent))
2306 }
2307
2308 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2309     let predicate_count = where_clause.predicates.len();
2310
2311     if config.where_single_line() && predicate_count == 1 {
2312         return false;
2313     }
2314     let brace_style = config.brace_style();
2315
2316     brace_style == BraceStyle::AlwaysNextLine
2317         || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2318 }
2319
2320 fn rewrite_generics(
2321     context: &RewriteContext,
2322     generics: &ast::Generics,
2323     shape: Shape,
2324     span: Span,
2325 ) -> Option<String> {
2326     let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2327     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2328     rewrite_generics_inner(context, generics, g_shape, one_line_width, span)
2329         .or_else(|| rewrite_generics_inner(context, generics, g_shape, 0, span))
2330 }
2331
2332 fn rewrite_generics_inner(
2333     context: &RewriteContext,
2334     generics: &ast::Generics,
2335     shape: Shape,
2336     one_line_width: usize,
2337     span: Span,
2338 ) -> Option<String> {
2339     // FIXME: convert bounds to where clauses where they get too big or if
2340     // there is a where clause at all.
2341
2342     // Wrapper type
2343     enum GenericsArg<'a> {
2344         Lifetime(&'a ast::LifetimeDef),
2345         TyParam(&'a ast::TyParam),
2346     }
2347     impl<'a> Rewrite for GenericsArg<'a> {
2348         fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2349             match *self {
2350                 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2351                 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2352             }
2353         }
2354     }
2355     impl<'a> Spanned for GenericsArg<'a> {
2356         fn span(&self) -> Span {
2357             match *self {
2358                 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2359                 GenericsArg::TyParam(ty) => ty.span(),
2360             }
2361         }
2362     }
2363
2364     if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2365         return Some(String::new());
2366     }
2367
2368     let generics_args = generics
2369         .lifetimes
2370         .iter()
2371         .map(|lt| GenericsArg::Lifetime(lt))
2372         .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2373     let items = itemize_list(
2374         context.codemap,
2375         generics_args,
2376         ">",
2377         ",",
2378         |arg| arg.span().lo(),
2379         |arg| arg.span().hi(),
2380         |arg| arg.rewrite(context, shape),
2381         context.codemap.span_after(span, "<"),
2382         span.hi(),
2383         false,
2384     );
2385     format_generics_item_list(context, items, shape, one_line_width)
2386 }
2387
2388 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2389     match config.indent_style() {
2390         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2391         IndentStyle::Block => {
2392             // 1 = ","
2393             shape
2394                 .block()
2395                 .block_indent(config.tab_spaces())
2396                 .with_max_width(config)
2397                 .sub_width(1)
2398         }
2399     }
2400 }
2401
2402 pub fn format_generics_item_list<I>(
2403     context: &RewriteContext,
2404     items: I,
2405     shape: Shape,
2406     one_line_budget: usize,
2407 ) -> Option<String>
2408 where
2409     I: Iterator<Item = ListItem>,
2410 {
2411     let item_vec = items.collect::<Vec<_>>();
2412
2413     let tactic = definitive_tactic(
2414         &item_vec,
2415         ListTactic::HorizontalVertical,
2416         Separator::Comma,
2417         one_line_budget,
2418     );
2419     let fmt = ListFormatting {
2420         tactic: tactic,
2421         separator: ",",
2422         trailing_separator: if context.config.indent_style() == IndentStyle::Visual {
2423             SeparatorTactic::Never
2424         } else {
2425             context.config.trailing_comma()
2426         },
2427         separator_place: SeparatorPlace::Back,
2428         shape: shape,
2429         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2430         preserve_newline: true,
2431         config: context.config,
2432     };
2433
2434     let list_str = write_list(&item_vec, &fmt)?;
2435
2436     Some(wrap_generics_with_angle_brackets(
2437         context,
2438         &list_str,
2439         shape.indent,
2440     ))
2441 }
2442
2443 pub fn wrap_generics_with_angle_brackets(
2444     context: &RewriteContext,
2445     list_str: &str,
2446     list_offset: Indent,
2447 ) -> String {
2448     if context.config.indent_style() == IndentStyle::Block
2449         && (list_str.contains('\n') || list_str.ends_with(','))
2450     {
2451         format!(
2452             "<\n{}{}\n{}>",
2453             list_offset.to_string(context.config),
2454             list_str,
2455             list_offset
2456                 .block_unindent(context.config)
2457                 .to_string(context.config)
2458         )
2459     } else if context.config.spaces_within_parens_and_brackets() {
2460         format!("< {} >", list_str)
2461     } else {
2462         format!("<{}>", list_str)
2463     }
2464 }
2465
2466 fn rewrite_trait_bounds(
2467     context: &RewriteContext,
2468     bounds: &[ast::TyParamBound],
2469     shape: Shape,
2470 ) -> Option<String> {
2471     if bounds.is_empty() {
2472         return Some(String::new());
2473     }
2474     let bound_str = bounds
2475         .iter()
2476         .map(|ty_bound| ty_bound.rewrite(context, shape))
2477         .collect::<Option<Vec<_>>>()?;
2478     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2479 }
2480
2481 fn rewrite_where_clause_rfc_style(
2482     context: &RewriteContext,
2483     where_clause: &ast::WhereClause,
2484     shape: Shape,
2485     terminator: &str,
2486     span_end: Option<BytePos>,
2487     span_end_before_where: BytePos,
2488     where_clause_option: WhereClauseOption,
2489     is_args_multi_line: bool,
2490 ) -> Option<String> {
2491     let block_shape = shape.block().with_max_width(context.config);
2492
2493     let (span_before, span_after) =
2494         missing_span_before_after_where(span_end_before_where, where_clause);
2495     let (comment_before, comment_after) =
2496         rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2497
2498     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2499         " ".to_owned()
2500     } else {
2501         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2502     };
2503
2504     let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2505     // 1 = `,`
2506     let clause_shape = clause_shape.sub_width(1)?;
2507     // each clause on one line, trailing comma (except if suppress_comma)
2508     let span_start = where_clause.predicates[0].span().lo();
2509     // If we don't have the start of the next span, then use the end of the
2510     // predicates, but that means we miss comments.
2511     let len = where_clause.predicates.len();
2512     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2513     let span_end = span_end.unwrap_or(end_of_preds);
2514     let items = itemize_list(
2515         context.codemap,
2516         where_clause.predicates.iter(),
2517         terminator,
2518         ",",
2519         |pred| pred.span().lo(),
2520         |pred| pred.span().hi(),
2521         |pred| pred.rewrite(context, clause_shape),
2522         span_start,
2523         span_end,
2524         false,
2525     );
2526     let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2527     let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2528         SeparatorTactic::Never
2529     } else {
2530         context.config.trailing_comma()
2531     };
2532
2533     // shape should be vertical only and only if we have `where_single_line` option enabled
2534     // and the number of items of the where clause is equal to 1
2535     let shape_tactic = if where_single_line {
2536         DefinitiveListTactic::Horizontal
2537     } else {
2538         DefinitiveListTactic::Vertical
2539     };
2540
2541     let fmt = ListFormatting {
2542         tactic: shape_tactic,
2543         separator: ",",
2544         trailing_separator: comma_tactic,
2545         separator_place: SeparatorPlace::Back,
2546         shape: clause_shape,
2547         ends_with_newline: true,
2548         preserve_newline: true,
2549         config: context.config,
2550     };
2551     let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2552
2553     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2554         String::new()
2555     } else {
2556         format!("\n{}", shape.indent.to_string(context.config))
2557     };
2558     let newline_before_where = comment_separator(&comment_before, shape);
2559     let newline_after_where = comment_separator(&comment_after, clause_shape);
2560
2561     // 6 = `where `
2562     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2563         && comment_after.is_empty() && !preds_str.contains('\n')
2564         && 6 + preds_str.len() <= shape.width || where_single_line
2565     {
2566         String::from(" ")
2567     } else {
2568         format!("\n{}", clause_shape.indent.to_string(context.config))
2569     };
2570     Some(format!(
2571         "{}{}{}where{}{}{}{}",
2572         starting_newline,
2573         comment_before,
2574         newline_before_where,
2575         newline_after_where,
2576         comment_after,
2577         clause_sep,
2578         preds_str
2579     ))
2580 }
2581
2582 fn rewrite_where_clause(
2583     context: &RewriteContext,
2584     where_clause: &ast::WhereClause,
2585     brace_style: BraceStyle,
2586     shape: Shape,
2587     density: Density,
2588     terminator: &str,
2589     span_end: Option<BytePos>,
2590     span_end_before_where: BytePos,
2591     where_clause_option: WhereClauseOption,
2592     is_args_multi_line: bool,
2593 ) -> Option<String> {
2594     if where_clause.predicates.is_empty() {
2595         return Some(String::new());
2596     }
2597
2598     if context.config.indent_style() == IndentStyle::Block {
2599         return rewrite_where_clause_rfc_style(
2600             context,
2601             where_clause,
2602             shape,
2603             terminator,
2604             span_end,
2605             span_end_before_where,
2606             where_clause_option,
2607             is_args_multi_line,
2608         );
2609     }
2610
2611     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2612
2613     let offset = match context.config.indent_style() {
2614         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2615         // 6 = "where ".len()
2616         IndentStyle::Visual => shape.indent + extra_indent + 6,
2617     };
2618     // FIXME: if indent_style != Visual, then the budgets below might
2619     // be out by a char or two.
2620
2621     let budget = context.config.max_width() - offset.width();
2622     let span_start = where_clause.predicates[0].span().lo();
2623     // If we don't have the start of the next span, then use the end of the
2624     // predicates, but that means we miss comments.
2625     let len = where_clause.predicates.len();
2626     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2627     let span_end = span_end.unwrap_or(end_of_preds);
2628     let items = itemize_list(
2629         context.codemap,
2630         where_clause.predicates.iter(),
2631         terminator,
2632         ",",
2633         |pred| pred.span().lo(),
2634         |pred| pred.span().hi(),
2635         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2636         span_start,
2637         span_end,
2638         false,
2639     );
2640     let item_vec = items.collect::<Vec<_>>();
2641     // FIXME: we don't need to collect here
2642     let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2643
2644     let mut comma_tactic = context.config.trailing_comma();
2645     // Kind of a hack because we don't usually have trailing commas in where clauses.
2646     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2647         comma_tactic = SeparatorTactic::Never;
2648     }
2649
2650     let fmt = ListFormatting {
2651         tactic: tactic,
2652         separator: ",",
2653         trailing_separator: comma_tactic,
2654         separator_place: SeparatorPlace::Back,
2655         shape: Shape::legacy(budget, offset),
2656         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2657         preserve_newline: true,
2658         config: context.config,
2659     };
2660     let preds_str = write_list(&item_vec, &fmt)?;
2661
2662     let end_length = if terminator == "{" {
2663         // If the brace is on the next line we don't need to count it otherwise it needs two
2664         // characters " {"
2665         match brace_style {
2666             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2667             BraceStyle::PreferSameLine => 2,
2668         }
2669     } else if terminator == "=" {
2670         2
2671     } else {
2672         terminator.len()
2673     };
2674     if density == Density::Tall || preds_str.contains('\n')
2675         || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2676     {
2677         Some(format!(
2678             "\n{}where {}",
2679             (shape.indent + extra_indent).to_string(context.config),
2680             preds_str
2681         ))
2682     } else {
2683         Some(format!(" where {}", preds_str))
2684     }
2685 }
2686
2687 fn missing_span_before_after_where(
2688     before_item_span_end: BytePos,
2689     where_clause: &ast::WhereClause,
2690 ) -> (Span, Span) {
2691     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2692     // 5 = `where`
2693     let pos_after_where = where_clause.span.lo() + BytePos(5);
2694     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2695     (missing_span_before, missing_span_after)
2696 }
2697
2698 fn rewrite_comments_before_after_where(
2699     context: &RewriteContext,
2700     span_before_where: Span,
2701     span_after_where: Span,
2702     shape: Shape,
2703 ) -> Option<(String, String)> {
2704     let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2705     let after_comment = rewrite_missing_comment(
2706         span_after_where,
2707         shape.block_indent(context.config.tab_spaces()),
2708         context,
2709     )?;
2710     Some((before_comment, after_comment))
2711 }
2712
2713 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2714     format!("{}{}{}", format_visibility(vis), item_name, ident)
2715 }
2716
2717 #[derive(PartialEq, Eq)]
2718 enum BracePos {
2719     None,
2720     Auto,
2721     ForceSameLine,
2722 }
2723
2724 fn format_generics(
2725     context: &RewriteContext,
2726     generics: &ast::Generics,
2727     brace_style: BraceStyle,
2728     brace_pos: BracePos,
2729     offset: Indent,
2730     span: Span,
2731     used_width: usize,
2732 ) -> Option<String> {
2733     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2734     let mut result = rewrite_generics(context, generics, shape, span)?;
2735
2736     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2737         let budget = context.budget(last_line_used_width(&result, offset.width()));
2738         let mut option = WhereClauseOption::snuggled(&result);
2739         if brace_pos == BracePos::None {
2740             option.suppress_comma = true;
2741         }
2742         // If the generics are not parameterized then generics.span.hi() == 0,
2743         // so we use span.lo(), which is the position after `struct Foo`.
2744         let span_end_before_where = if generics.is_parameterized() {
2745             generics.span.hi()
2746         } else {
2747             span.lo()
2748         };
2749         let where_clause_str = rewrite_where_clause(
2750             context,
2751             &generics.where_clause,
2752             brace_style,
2753             Shape::legacy(budget, offset.block_only()),
2754             Density::Tall,
2755             "{",
2756             Some(span.hi()),
2757             span_end_before_where,
2758             option,
2759             false,
2760         )?;
2761         result.push_str(&where_clause_str);
2762         brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2763             || (generics.where_clause.predicates.is_empty()
2764                 && trimmed_last_line_width(&result) == 1)
2765     } else {
2766         brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2767             || brace_style != BraceStyle::AlwaysNextLine
2768     };
2769     if brace_pos == BracePos::None {
2770         return Some(result);
2771     }
2772     let total_used_width = last_line_used_width(&result, used_width);
2773     let remaining_budget = context.budget(total_used_width);
2774     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2775     // and hence we take the closer into account as well for one line budget.
2776     // We assume that the closer has the same length as the opener.
2777     let overhead = if brace_pos == BracePos::ForceSameLine {
2778         // 3 = ` {}`
2779         3
2780     } else {
2781         // 2 = ` {`
2782         2
2783     };
2784     let forbid_same_line_brace = overhead > remaining_budget;
2785     if !forbid_same_line_brace && same_line_brace {
2786         result.push(' ');
2787     } else {
2788         result.push('\n');
2789         result.push_str(&offset.block_only().to_string(context.config));
2790     }
2791     result.push('{');
2792
2793     Some(result)
2794 }
2795
2796 impl Rewrite for ast::ForeignItem {
2797     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2798         let attrs_str = self.attrs.rewrite(context, shape)?;
2799         // Drop semicolon or it will be interpreted as comment.
2800         // FIXME: this may be a faulty span from libsyntax.
2801         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2802
2803         let item_str = match self.node {
2804             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2805                 rewrite_fn_base(
2806                     context,
2807                     shape.indent,
2808                     self.ident,
2809                     &FnSig::new(fn_decl, generics, self.vis.clone()),
2810                     span,
2811                     false,
2812                     false,
2813                 ).map(|(s, _)| format!("{};", s))
2814             }
2815             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2816                 // FIXME(#21): we're dropping potential comments in between the
2817                 // function keywords here.
2818                 let vis = format_visibility(&self.vis);
2819                 let mut_str = if is_mutable { "mut " } else { "" };
2820                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2821                 // 1 = ;
2822                 let shape = shape.sub_width(1)?;
2823                 ty.rewrite(context, shape).map(|ty_str| {
2824                     // 1 = space between prefix and type.
2825                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2826                         String::from(" ")
2827                     } else {
2828                         let nested_indent = shape.indent.block_indent(context.config);
2829                         format!("\n{}", nested_indent.to_string(context.config))
2830                     };
2831                     format!("{}{}{};", prefix, sep, ty_str)
2832                 })
2833             }
2834             ast::ForeignItemKind::Ty => {
2835                 let vis = format_visibility(&self.vis);
2836                 Some(format!("{}type {};", vis, self.ident))
2837             }
2838         }?;
2839
2840         let missing_span = if self.attrs.is_empty() {
2841             mk_sp(self.span.lo(), self.span.lo())
2842         } else {
2843             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2844         };
2845         combine_strs_with_missing_comments(
2846             context,
2847             &attrs_str,
2848             &item_str,
2849             missing_span,
2850             shape,
2851             false,
2852         )
2853     }
2854 }