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