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