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