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