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