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