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