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