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