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