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