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