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