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