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