]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Remove unnecessary wrap_str()
[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!(
1215             rewrite_call_inner(
1216                 context,
1217                 "",
1218                 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1219                 span,
1220                 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1221                 context.config.fn_call_width(),
1222                 false,
1223             ).ok()
1224         );
1225         result.push_str(&body);
1226     }
1227
1228     if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1229         && (result.contains('\n')
1230             || offset.block_indent + result.len() + where_clause_str.len() + 1
1231                 > context.config.max_width())
1232     {
1233         // We need to put the where clause on a new line, but we didn't
1234         // know that earlier, so the where clause will not be indented properly.
1235         result.push('\n');
1236         result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1237             .to_string(context.config));
1238     }
1239     result.push_str(&where_clause_str);
1240
1241     Some(result)
1242 }
1243
1244 pub fn rewrite_type_alias(
1245     context: &RewriteContext,
1246     indent: Indent,
1247     ident: ast::Ident,
1248     ty: &ast::Ty,
1249     generics: &ast::Generics,
1250     vis: &ast::Visibility,
1251     span: Span,
1252 ) -> Option<String> {
1253     let mut result = String::with_capacity(128);
1254
1255     result.push_str(&format_visibility(vis));
1256     result.push_str("type ");
1257     result.push_str(&ident.to_string());
1258
1259     // 2 = `= `
1260     let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1261     let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1262     let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1263     result.push_str(&generics_str);
1264
1265     let where_budget = context.budget(last_line_width(&result));
1266     let option = WhereClauseOption::snuggled(&result);
1267     let where_clause_str = try_opt!(rewrite_where_clause(
1268         context,
1269         &generics.where_clause,
1270         context.config.item_brace_style(),
1271         Shape::legacy(where_budget, indent),
1272         context.config.where_density(),
1273         "=",
1274         Some(span.hi()),
1275         generics.span.hi(),
1276         option,
1277     ));
1278     result.push_str(&where_clause_str);
1279     if where_clause_str.is_empty() {
1280         result.push_str(" = ");
1281     } else {
1282         result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1283     }
1284
1285     let line_width = last_line_width(&result);
1286     // This checked_sub may fail as the extra space after '=' is not taken into account
1287     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1288     let budget = context.budget(indent.width() + line_width + ";".len());
1289     let type_indent = indent + line_width;
1290     // Try to fit the type on the same line
1291     let ty_str = try_opt!(
1292         ty.rewrite(context, Shape::legacy(budget, type_indent))
1293             .or_else(|| {
1294                 // The line was too short, try to put the type on the next line
1295
1296                 // Remove the space after '='
1297                 result.pop();
1298                 let type_indent = indent.block_indent(context.config);
1299                 result.push('\n');
1300                 result.push_str(&type_indent.to_string(context.config));
1301                 let budget = context.budget(type_indent.width() + ";".len());
1302                 ty.rewrite(context, Shape::legacy(budget, type_indent))
1303             })
1304     );
1305     result.push_str(&ty_str);
1306     result.push_str(";");
1307     Some(result)
1308 }
1309
1310 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1311     (
1312         if config.space_before_type_annotation() {
1313             " "
1314         } else {
1315             ""
1316         },
1317         if config.space_after_type_annotation_colon() {
1318             " "
1319         } else {
1320             ""
1321         },
1322     )
1323 }
1324
1325 pub fn rewrite_struct_field_prefix(
1326     context: &RewriteContext,
1327     field: &ast::StructField,
1328 ) -> Option<String> {
1329     let vis = format_visibility(&field.vis);
1330     let type_annotation_spacing = type_annotation_spacing(context.config);
1331     Some(match field.ident {
1332         Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1333         None => format!("{}", vis),
1334     })
1335 }
1336
1337 fn rewrite_struct_field_type(
1338     context: &RewriteContext,
1339     last_line_width: usize,
1340     field: &ast::StructField,
1341     spacing: &str,
1342     shape: Shape,
1343 ) -> Option<String> {
1344     let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1345     field
1346         .ty
1347         .rewrite(context, ty_shape)
1348         .map(|ty| format!("{}{}", spacing, ty))
1349 }
1350
1351 impl Rewrite for ast::StructField {
1352     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1353         rewrite_struct_field(context, self, shape, 0)
1354     }
1355 }
1356
1357 pub fn rewrite_struct_field(
1358     context: &RewriteContext,
1359     field: &ast::StructField,
1360     shape: Shape,
1361     lhs_max_width: usize,
1362 ) -> Option<String> {
1363     if contains_skip(&field.attrs) {
1364         return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1365     }
1366
1367     let type_annotation_spacing = type_annotation_spacing(context.config);
1368     let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1369
1370     let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1371     let attrs_extendable = attrs_str.is_empty()
1372         || (context.config.attributes_on_same_line_as_field()
1373             && is_attributes_extendable(&attrs_str));
1374     let missing_span = if field.attrs.is_empty() {
1375         mk_sp(field.span.lo(), field.span.lo())
1376     } else {
1377         mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1378     };
1379     let mut spacing = String::from(if field.ident.is_some() {
1380         type_annotation_spacing.1
1381     } else {
1382         ""
1383     });
1384     // Try to put everything on a single line.
1385     let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1386         context,
1387         &attrs_str,
1388         &prefix,
1389         missing_span,
1390         shape,
1391         attrs_extendable,
1392     ));
1393     let overhead = last_line_width(&attr_prefix);
1394     let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1395     for _ in 0..lhs_offset {
1396         spacing.push(' ');
1397     }
1398     // In this extreme case we will be missing a space betweeen an attribute and a field.
1399     if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1400         spacing.push(' ');
1401     }
1402     let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1403     if let Some(ref ty) = ty_rewritten {
1404         if !ty.contains('\n') {
1405             return Some(attr_prefix + ty);
1406         }
1407     }
1408
1409     // We must use multiline.
1410     let last_line_width = last_line_width(&prefix);
1411     let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1412
1413     let type_offset = shape.indent.block_indent(context.config);
1414     let rewrite_type_in_next_line = || {
1415         field
1416             .ty
1417             .rewrite(context, Shape::indented(type_offset, context.config))
1418     };
1419
1420     let field_str = match ty_rewritten {
1421         // If we start from the next line and type fits in a single line, then do so.
1422         Some(ref ty) => match rewrite_type_in_next_line() {
1423             Some(ref new_ty) if !new_ty.contains('\n') => format!(
1424                 "{}\n{}{}",
1425                 prefix,
1426                 type_offset.to_string(context.config),
1427                 &new_ty
1428             ),
1429             _ => prefix + ty,
1430         },
1431         _ => {
1432             let ty = try_opt!(rewrite_type_in_next_line());
1433             format!(
1434                 "{}\n{}{}",
1435                 prefix,
1436                 type_offset.to_string(context.config),
1437                 &ty
1438             )
1439         }
1440     };
1441     combine_strs_with_missing_comments(
1442         context,
1443         &attrs_str,
1444         &field_str,
1445         missing_span,
1446         shape,
1447         attrs_extendable,
1448     )
1449 }
1450
1451 pub fn rewrite_static(
1452     prefix: &str,
1453     vis: &ast::Visibility,
1454     ident: ast::Ident,
1455     ty: &ast::Ty,
1456     mutability: ast::Mutability,
1457     expr_opt: Option<&ptr::P<ast::Expr>>,
1458     offset: Indent,
1459     span: Span,
1460     context: &RewriteContext,
1461 ) -> Option<String> {
1462     let colon = colon_spaces(
1463         context.config.space_before_type_annotation(),
1464         context.config.space_after_type_annotation_colon(),
1465     );
1466     let prefix = format!(
1467         "{}{} {}{}{}",
1468         format_visibility(vis),
1469         prefix,
1470         format_mutability(mutability),
1471         ident,
1472         colon,
1473     );
1474     // 2 = " =".len()
1475     let ty_str = try_opt!(ty.rewrite(
1476         context,
1477         try_opt!(
1478             Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1479         ),
1480     ));
1481
1482     if let Some(expr) = expr_opt {
1483         let lhs = format!("{}{} =", prefix, ty_str);
1484         // 1 = ;
1485         let remaining_width = context.budget(offset.block_indent + 1);
1486         rewrite_assign_rhs(
1487             context,
1488             lhs,
1489             expr,
1490             Shape::legacy(remaining_width, offset.block_only()),
1491         ).and_then(|res| recover_comment_removed(res, span, context))
1492             .map(|s| if s.ends_with(';') { s } else { s + ";" })
1493     } else {
1494         Some(format!("{}{};", prefix, ty_str))
1495     }
1496 }
1497
1498 pub fn rewrite_associated_type(
1499     ident: ast::Ident,
1500     ty_opt: Option<&ptr::P<ast::Ty>>,
1501     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1502     context: &RewriteContext,
1503     indent: Indent,
1504 ) -> Option<String> {
1505     let prefix = format!("type {}", ident);
1506
1507     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1508         // 2 = ": ".len()
1509         let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1510         let bounds: &[_] = ty_param_bounds;
1511         let bound_str = try_opt!(
1512             bounds
1513                 .iter()
1514                 .map(|ty_bound| ty_bound.rewrite(context, shape))
1515                 .collect::<Option<Vec<_>>>()
1516         );
1517         if !bounds.is_empty() {
1518             format!(": {}", join_bounds(context, shape, &bound_str))
1519         } else {
1520             String::new()
1521         }
1522     } else {
1523         String::new()
1524     };
1525
1526     if let Some(ty) = ty_opt {
1527         let ty_str = try_opt!(ty.rewrite(
1528             context,
1529             Shape::legacy(
1530                 context.budget(indent.block_indent + prefix.len() + 2),
1531                 indent.block_only(),
1532             ),
1533         ));
1534         Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1535     } else {
1536         Some(format!("{}{};", prefix, type_bounds_str))
1537     }
1538 }
1539
1540 pub fn rewrite_associated_impl_type(
1541     ident: ast::Ident,
1542     defaultness: ast::Defaultness,
1543     ty_opt: Option<&ptr::P<ast::Ty>>,
1544     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1545     context: &RewriteContext,
1546     indent: Indent,
1547 ) -> Option<String> {
1548     let result = try_opt!(rewrite_associated_type(
1549         ident,
1550         ty_opt,
1551         ty_param_bounds_opt,
1552         context,
1553         indent,
1554     ));
1555
1556     match defaultness {
1557         ast::Defaultness::Default => Some(format!("default {}", result)),
1558         _ => Some(result),
1559     }
1560 }
1561
1562 impl Rewrite for ast::FunctionRetTy {
1563     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1564         match *self {
1565             ast::FunctionRetTy::Default(_) => Some(String::new()),
1566             ast::FunctionRetTy::Ty(ref ty) => {
1567                 let inner_width = try_opt!(shape.width.checked_sub(3));
1568                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1569                     .map(|r| format!("-> {}", r))
1570             }
1571         }
1572     }
1573 }
1574
1575 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1576     match ty.node {
1577         ast::TyKind::Infer => {
1578             let original = context.snippet(ty.span);
1579             original != "_"
1580         }
1581         _ => false,
1582     }
1583 }
1584
1585 impl Rewrite for ast::Arg {
1586     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1587         if is_named_arg(self) {
1588             let mut result = try_opt!(
1589                 self.pat
1590                     .rewrite(context, Shape::legacy(shape.width, shape.indent))
1591             );
1592
1593             if !is_empty_infer(context, &*self.ty) {
1594                 if context.config.space_before_type_annotation() {
1595                     result.push_str(" ");
1596                 }
1597                 result.push_str(":");
1598                 if context.config.space_after_type_annotation_colon() {
1599                     result.push_str(" ");
1600                 }
1601                 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1602                 let ty_str = try_opt!(self.ty.rewrite(
1603                     context,
1604                     Shape::legacy(max_width, shape.indent + result.len()),
1605                 ));
1606                 result.push_str(&ty_str);
1607             }
1608
1609             Some(result)
1610         } else {
1611             self.ty.rewrite(context, shape)
1612         }
1613     }
1614 }
1615
1616 fn rewrite_explicit_self(
1617     explicit_self: &ast::ExplicitSelf,
1618     args: &[ast::Arg],
1619     context: &RewriteContext,
1620 ) -> Option<String> {
1621     match explicit_self.node {
1622         ast::SelfKind::Region(lt, m) => {
1623             let mut_str = format_mutability(m);
1624             match lt {
1625                 Some(ref l) => {
1626                     let lifetime_str = try_opt!(l.rewrite(
1627                         context,
1628                         Shape::legacy(context.config.max_width(), Indent::empty()),
1629                     ));
1630                     Some(format!("&{} {}self", lifetime_str, mut_str))
1631                 }
1632                 None => Some(format!("&{}self", mut_str)),
1633             }
1634         }
1635         ast::SelfKind::Explicit(ref ty, _) => {
1636             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1637
1638             let mutability = explicit_self_mutability(&args[0]);
1639             let type_str = try_opt!(ty.rewrite(
1640                 context,
1641                 Shape::legacy(context.config.max_width(), Indent::empty()),
1642             ));
1643
1644             Some(format!(
1645                 "{}self: {}",
1646                 format_mutability(mutability),
1647                 type_str
1648             ))
1649         }
1650         ast::SelfKind::Value(_) => {
1651             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1652
1653             let mutability = explicit_self_mutability(&args[0]);
1654
1655             Some(format!("{}self", format_mutability(mutability)))
1656         }
1657     }
1658 }
1659
1660 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1661 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1662 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1663     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1664         mutability
1665     } else {
1666         unreachable!()
1667     }
1668 }
1669
1670 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1671     if is_named_arg(arg) {
1672         arg.pat.span.lo()
1673     } else {
1674         arg.ty.span.lo()
1675     }
1676 }
1677
1678 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1679     match arg.ty.node {
1680         ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1681         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1682         _ => arg.ty.span.hi(),
1683     }
1684 }
1685
1686 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1687     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1688         ident.node != symbol::keywords::Invalid.ident()
1689     } else {
1690         true
1691     }
1692 }
1693
1694 // Return type is (result, force_new_line_for_brace)
1695 fn rewrite_fn_base(
1696     context: &RewriteContext,
1697     indent: Indent,
1698     ident: ast::Ident,
1699     fd: &ast::FnDecl,
1700     generics: &ast::Generics,
1701     unsafety: ast::Unsafety,
1702     constness: ast::Constness,
1703     defaultness: ast::Defaultness,
1704     abi: abi::Abi,
1705     vis: &ast::Visibility,
1706     span: Span,
1707     newline_brace: bool,
1708     has_body: bool,
1709     has_braces: bool,
1710 ) -> Option<(String, bool)> {
1711     let mut force_new_line_for_brace = false;
1712
1713     let where_clause = &generics.where_clause;
1714
1715     let mut result = String::with_capacity(1024);
1716     // Vis defaultness constness unsafety abi.
1717     result.push_str(&*format_visibility(vis));
1718     result.push_str(format_defaultness(defaultness));
1719     result.push_str(format_constness(constness));
1720     result.push_str(format_unsafety(unsafety));
1721     if abi != abi::Abi::Rust {
1722         result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1723     }
1724
1725     // fn foo
1726     result.push_str("fn ");
1727     result.push_str(&ident.to_string());
1728
1729     // Generics.
1730     let overhead = if has_braces && !newline_brace {
1731         // 4 = `() {`
1732         4
1733     } else {
1734         // 2 = `()`
1735         2
1736     };
1737     let used_width = last_line_used_width(&result, indent.width());
1738     let one_line_budget = context.budget(used_width + overhead);
1739     let shape = Shape {
1740         width: one_line_budget,
1741         indent: indent,
1742         offset: used_width,
1743     };
1744     let g_span = mk_sp(span.lo(), fd.output.span().lo());
1745     let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1746     result.push_str(&generics_str);
1747
1748     let snuggle_angle_bracket = generics_str
1749         .lines()
1750         .last()
1751         .map_or(false, |l| l.trim_left().len() == 1);
1752
1753     // Note that the width and indent don't really matter, we'll re-layout the
1754     // return type later anyway.
1755     let ret_str = try_opt!(
1756         fd.output
1757             .rewrite(context, Shape::indented(indent, context.config))
1758     );
1759
1760     let multi_line_ret_str = ret_str.contains('\n');
1761     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1762
1763     // Args.
1764     let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1765         context,
1766         &result,
1767         indent,
1768         ret_str_len,
1769         newline_brace,
1770         has_braces,
1771         multi_line_ret_str,
1772     ));
1773
1774     debug!(
1775         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1776         one_line_budget,
1777         multi_line_budget,
1778         arg_indent
1779     );
1780
1781     // Check if vertical layout was forced.
1782     if one_line_budget == 0 {
1783         if snuggle_angle_bracket {
1784             result.push('(');
1785         } else if context.config.fn_args_paren_newline() {
1786             result.push('\n');
1787             result.push_str(&arg_indent.to_string(context.config));
1788             if context.config.fn_args_layout() == IndentStyle::Visual {
1789                 arg_indent = arg_indent + 1; // extra space for `(`
1790             }
1791             result.push('(');
1792         } else {
1793             result.push_str("(");
1794             if context.config.fn_args_layout() == IndentStyle::Visual {
1795                 result.push('\n');
1796                 result.push_str(&arg_indent.to_string(context.config));
1797             }
1798         }
1799     } else {
1800         result.push('(');
1801     }
1802     if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1803         result.push(' ')
1804     }
1805
1806     // A conservative estimation, to goal is to be over all parens in generics
1807     let args_start = generics
1808         .ty_params
1809         .last()
1810         .map_or(span.lo(), |tp| end_typaram(tp));
1811     let args_end = if fd.inputs.is_empty() {
1812         context
1813             .codemap
1814             .span_after(mk_sp(args_start, span.hi()), ")")
1815     } else {
1816         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1817         context.codemap.span_after(last_span, ")")
1818     };
1819     let args_span = mk_sp(
1820         context
1821             .codemap
1822             .span_after(mk_sp(args_start, span.hi()), "("),
1823         args_end,
1824     );
1825     let arg_str = try_opt!(rewrite_args(
1826         context,
1827         &fd.inputs,
1828         fd.get_self().as_ref(),
1829         one_line_budget,
1830         multi_line_budget,
1831         indent,
1832         arg_indent,
1833         args_span,
1834         fd.variadic,
1835         generics_str.contains('\n'),
1836     ));
1837
1838     let put_args_in_block = match context.config.fn_args_layout() {
1839         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1840         _ => false,
1841     } && !fd.inputs.is_empty();
1842
1843     let mut args_last_line_contains_comment = false;
1844     if put_args_in_block {
1845         arg_indent = indent.block_indent(context.config);
1846         result.push('\n');
1847         result.push_str(&arg_indent.to_string(context.config));
1848         result.push_str(&arg_str);
1849         result.push('\n');
1850         result.push_str(&indent.to_string(context.config));
1851         result.push(')');
1852     } else {
1853         result.push_str(&arg_str);
1854         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1855         // Put the closing brace on the next line if it overflows the max width.
1856         // 1 = `)`
1857         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1858             result.push('\n');
1859         }
1860         if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1861             result.push(' ')
1862         }
1863         // If the last line of args contains comment, we cannot put the closing paren
1864         // on the same line.
1865         if arg_str
1866             .lines()
1867             .last()
1868             .map_or(false, |last_line| last_line.contains("//"))
1869         {
1870             args_last_line_contains_comment = true;
1871             result.push('\n');
1872             result.push_str(&arg_indent.to_string(context.config));
1873         }
1874         result.push(')');
1875     }
1876
1877     // Return type.
1878     if let ast::FunctionRetTy::Ty(..) = fd.output {
1879         let ret_should_indent = match context.config.fn_args_layout() {
1880             // If our args are block layout then we surely must have space.
1881             IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1882             _ if args_last_line_contains_comment => false,
1883             _ if result.contains('\n') || multi_line_ret_str => true,
1884             _ => {
1885                 // If the return type would push over the max width, then put the return type on
1886                 // a new line. With the +1 for the signature length an additional space between
1887                 // the closing parenthesis of the argument and the arrow '->' is considered.
1888                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1889
1890                 // If there is no where clause, take into account the space after the return type
1891                 // and the brace.
1892                 if where_clause.predicates.is_empty() {
1893                     sig_length += 2;
1894                 }
1895
1896                 sig_length > context.config.max_width()
1897             }
1898         };
1899         let ret_indent = if ret_should_indent {
1900             let indent = match context.config.fn_return_indent() {
1901                 ReturnIndent::WithWhereClause => indent + 4,
1902                 // Aligning with non-existent args looks silly.
1903                 _ if arg_str.is_empty() => {
1904                     force_new_line_for_brace = true;
1905                     indent + 4
1906                 }
1907                 // FIXME: we might want to check that using the arg indent
1908                 // doesn't blow our budget, and if it does, then fallback to
1909                 // the where clause indent.
1910                 _ => arg_indent,
1911             };
1912
1913             result.push('\n');
1914             result.push_str(&indent.to_string(context.config));
1915             indent
1916         } else {
1917             result.push(' ');
1918             Indent::new(indent.block_indent, last_line_width(&result))
1919         };
1920
1921         if multi_line_ret_str || ret_should_indent {
1922             // Now that we know the proper indent and width, we need to
1923             // re-layout the return type.
1924             let ret_str = try_opt!(
1925                 fd.output
1926                     .rewrite(context, Shape::indented(ret_indent, context.config))
1927             );
1928             result.push_str(&ret_str);
1929         } else {
1930             result.push_str(&ret_str);
1931         }
1932
1933         // Comment between return type and the end of the decl.
1934         let snippet_lo = fd.output.span().hi();
1935         if where_clause.predicates.is_empty() {
1936             let snippet_hi = span.hi();
1937             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1938             // Try to preserve the layout of the original snippet.
1939             let original_starts_with_newline = snippet
1940                 .find(|c| c != ' ')
1941                 .map_or(false, |i| snippet[i..].starts_with('\n'));
1942             let original_ends_with_newline = snippet
1943                 .rfind(|c| c != ' ')
1944                 .map_or(false, |i| snippet[i..].ends_with('\n'));
1945             let snippet = snippet.trim();
1946             if !snippet.is_empty() {
1947                 result.push(if original_starts_with_newline {
1948                     '\n'
1949                 } else {
1950                     ' '
1951                 });
1952                 result.push_str(snippet);
1953                 if original_ends_with_newline {
1954                     force_new_line_for_brace = true;
1955                 }
1956             }
1957         }
1958     }
1959
1960     let should_compress_where = match context.config.where_density() {
1961         Density::Compressed => !result.contains('\n'),
1962         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1963         _ => false,
1964     };
1965
1966     let pos_before_where = match fd.output {
1967         ast::FunctionRetTy::Default(..) => args_span.hi(),
1968         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1969     };
1970
1971     if where_clause.predicates.len() == 1 && should_compress_where {
1972         let budget = context.budget(last_line_used_width(&result, indent.width()));
1973         if let Some(where_clause_str) = rewrite_where_clause(
1974             context,
1975             where_clause,
1976             context.config.fn_brace_style(),
1977             Shape::legacy(budget, indent),
1978             Density::Compressed,
1979             "{",
1980             Some(span.hi()),
1981             pos_before_where,
1982             WhereClauseOption::compressed(),
1983         ) {
1984             result.push_str(&where_clause_str);
1985             force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1986             return Some((result, force_new_line_for_brace));
1987         }
1988     }
1989
1990     let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
1991     let where_clause_str = try_opt!(rewrite_where_clause(
1992         context,
1993         where_clause,
1994         context.config.fn_brace_style(),
1995         Shape::indented(indent, context.config),
1996         Density::Tall,
1997         "{",
1998         Some(span.hi()),
1999         pos_before_where,
2000         option,
2001     ));
2002     // If there are neither where clause nor return type, we may be missing comments between
2003     // args and `{`.
2004     if where_clause_str.is_empty() {
2005         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2006             match recover_missing_comment_in_span(
2007                 mk_sp(args_span.hi(), ret_span.hi()),
2008                 shape,
2009                 context,
2010                 last_line_width(&result),
2011             ) {
2012                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2013                     result.push_str(missing_comment);
2014                     force_new_line_for_brace = true;
2015                 }
2016                 _ => (),
2017             }
2018         }
2019     }
2020
2021     result.push_str(&where_clause_str);
2022
2023     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2024     Some((result, force_new_line_for_brace))
2025 }
2026
2027 #[derive(Copy, Clone)]
2028 struct WhereClauseOption {
2029     suppress_comma: bool, // Force no trailing comma
2030     snuggle: bool,        // Do not insert newline before `where`
2031     compress_where: bool, // Try single line where clause instead of vertical layout
2032 }
2033
2034 impl WhereClauseOption {
2035     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2036         WhereClauseOption {
2037             suppress_comma: suppress_comma,
2038             snuggle: snuggle,
2039             compress_where: false,
2040         }
2041     }
2042
2043     pub fn compressed() -> WhereClauseOption {
2044         WhereClauseOption {
2045             suppress_comma: true,
2046             snuggle: false,
2047             compress_where: true,
2048         }
2049     }
2050
2051     pub fn snuggled(current: &str) -> WhereClauseOption {
2052         WhereClauseOption {
2053             suppress_comma: false,
2054             snuggle: trimmed_last_line_width(current) == 1,
2055             compress_where: false,
2056         }
2057     }
2058 }
2059
2060 fn rewrite_args(
2061     context: &RewriteContext,
2062     args: &[ast::Arg],
2063     explicit_self: Option<&ast::ExplicitSelf>,
2064     one_line_budget: usize,
2065     multi_line_budget: usize,
2066     indent: Indent,
2067     arg_indent: Indent,
2068     span: Span,
2069     variadic: bool,
2070     generics_str_contains_newline: bool,
2071 ) -> Option<String> {
2072     let mut arg_item_strs = try_opt!(
2073         args.iter()
2074             .map(|arg| {
2075                 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2076             })
2077             .collect::<Option<Vec<_>>>()
2078     );
2079
2080     // Account for sugary self.
2081     // FIXME: the comment for the self argument is dropped. This is blocked
2082     // on rust issue #27522.
2083     let min_args = explicit_self
2084         .and_then(|explicit_self| {
2085             rewrite_explicit_self(explicit_self, args, context)
2086         })
2087         .map_or(1, |self_str| {
2088             arg_item_strs[0] = self_str;
2089             2
2090         });
2091
2092     // Comments between args.
2093     let mut arg_items = Vec::new();
2094     if min_args == 2 {
2095         arg_items.push(ListItem::from_str(""));
2096     }
2097
2098     // FIXME(#21): if there are no args, there might still be a comment, but
2099     // without spans for the comment or parens, there is no chance of
2100     // getting it right. You also don't get to put a comment on self, unless
2101     // it is explicit.
2102     if args.len() >= min_args || variadic {
2103         let comment_span_start = if min_args == 2 {
2104             let second_arg_start = if arg_has_pattern(&args[1]) {
2105                 args[1].pat.span.lo()
2106             } else {
2107                 args[1].ty.span.lo()
2108             };
2109             let reduced_span = mk_sp(span.lo(), second_arg_start);
2110
2111             context.codemap.span_after_last(reduced_span, ",")
2112         } else {
2113             span.lo()
2114         };
2115
2116         enum ArgumentKind<'a> {
2117             Regular(&'a ast::Arg),
2118             Variadic(BytePos),
2119         }
2120
2121         let variadic_arg = if variadic {
2122             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2123             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2124             Some(ArgumentKind::Variadic(variadic_start))
2125         } else {
2126             None
2127         };
2128
2129         let more_items = itemize_list(
2130             context.codemap,
2131             args[min_args - 1..]
2132                 .iter()
2133                 .map(ArgumentKind::Regular)
2134                 .chain(variadic_arg),
2135             ")",
2136             |arg| match *arg {
2137                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2138                 ArgumentKind::Variadic(start) => start,
2139             },
2140             |arg| match *arg {
2141                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2142                 ArgumentKind::Variadic(start) => start + BytePos(3),
2143             },
2144             |arg| match *arg {
2145                 ArgumentKind::Regular(..) => None,
2146                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2147             },
2148             comment_span_start,
2149             span.hi(),
2150             false,
2151         );
2152
2153         arg_items.extend(more_items);
2154     }
2155
2156     let fits_in_one_line = !generics_str_contains_newline
2157         && (arg_items.is_empty()
2158             || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2159
2160     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2161         item.item = Some(arg);
2162     }
2163
2164     let last_line_ends_with_comment = arg_items
2165         .iter()
2166         .last()
2167         .and_then(|item| item.post_comment.as_ref())
2168         .map_or(false, |s| s.trim().starts_with("//"));
2169
2170     let (indent, trailing_comma) = match context.config.fn_args_layout() {
2171         IndentStyle::Block if fits_in_one_line => {
2172             (indent.block_indent(context.config), SeparatorTactic::Never)
2173         }
2174         IndentStyle::Block => (
2175             indent.block_indent(context.config),
2176             context.config.trailing_comma(),
2177         ),
2178         IndentStyle::Visual if last_line_ends_with_comment => {
2179             (arg_indent, context.config.trailing_comma())
2180         }
2181         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2182     };
2183
2184     let tactic = definitive_tactic(
2185         &arg_items,
2186         context.config.fn_args_density().to_list_tactic(),
2187         Separator::Comma,
2188         one_line_budget,
2189     );
2190     let budget = match tactic {
2191         DefinitiveListTactic::Horizontal => one_line_budget,
2192         _ => multi_line_budget,
2193     };
2194
2195     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2196
2197     let fmt = ListFormatting {
2198         tactic: tactic,
2199         separator: ",",
2200         trailing_separator: if variadic {
2201             SeparatorTactic::Never
2202         } else {
2203             trailing_comma
2204         },
2205         separator_place: SeparatorPlace::Back,
2206         shape: Shape::legacy(budget, indent),
2207         ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2208         preserve_newline: true,
2209         config: context.config,
2210     };
2211
2212     write_list(&arg_items, &fmt)
2213 }
2214
2215 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2216     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2217         ident.node != symbol::keywords::Invalid.ident()
2218     } else {
2219         true
2220     }
2221 }
2222
2223 fn compute_budgets_for_args(
2224     context: &RewriteContext,
2225     result: &str,
2226     indent: Indent,
2227     ret_str_len: usize,
2228     newline_brace: bool,
2229     has_braces: bool,
2230     force_vertical_layout: bool,
2231 ) -> Option<((usize, usize, Indent))> {
2232     debug!(
2233         "compute_budgets_for_args {} {:?}, {}, {}",
2234         result.len(),
2235         indent,
2236         ret_str_len,
2237         newline_brace
2238     );
2239     // Try keeping everything on the same line.
2240     if !result.contains('\n') && !force_vertical_layout {
2241         // 2 = `()`, 3 = `() `, space is before ret_string.
2242         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2243         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2244         if has_braces {
2245             if !newline_brace {
2246                 // 2 = `{}`
2247                 used_space += 2;
2248             }
2249         } else {
2250             // 1 = `;`
2251             used_space += 1;
2252         }
2253         let one_line_budget = context.budget(used_space);
2254
2255         if one_line_budget > 0 {
2256             // 4 = "() {".len()
2257             let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2258                 IndentStyle::Block => {
2259                     let indent = indent.block_indent(context.config);
2260                     (indent, context.budget(indent.width() + 1))
2261                 }
2262                 IndentStyle::Visual => {
2263                     let indent = indent + result.len() + 1;
2264                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2265                     (indent, context.budget(multi_line_overhead))
2266                 }
2267             };
2268
2269             return Some((one_line_budget, multi_line_budget, indent));
2270         }
2271     }
2272
2273     // Didn't work. we must force vertical layout and put args on a newline.
2274     let new_indent = indent.block_indent(context.config);
2275     let used_space = match context.config.fn_args_layout() {
2276         // 1 = `,`
2277         IndentStyle::Block => new_indent.width() + 1,
2278         // Account for `)` and possibly ` {`.
2279         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2280     };
2281     Some((0, context.budget(used_space), new_indent))
2282 }
2283
2284 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2285     match (config.fn_brace_style(), config.where_density()) {
2286         (BraceStyle::AlwaysNextLine, _) => true,
2287         (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2288         (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2289         (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2290         _ => false,
2291     }
2292 }
2293
2294 fn rewrite_generics(
2295     context: &RewriteContext,
2296     generics: &ast::Generics,
2297     shape: Shape,
2298     span: Span,
2299 ) -> Option<String> {
2300     let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2301     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2302     rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2303         rewrite_generics_inner(context, generics, g_shape, 0, span)
2304     })
2305 }
2306
2307 fn rewrite_generics_inner(
2308     context: &RewriteContext,
2309     generics: &ast::Generics,
2310     shape: Shape,
2311     one_line_width: usize,
2312     span: Span,
2313 ) -> Option<String> {
2314     // FIXME: convert bounds to where clauses where they get too big or if
2315     // there is a where clause at all.
2316
2317     // Wrapper type
2318     enum GenericsArg<'a> {
2319         Lifetime(&'a ast::LifetimeDef),
2320         TyParam(&'a ast::TyParam),
2321     }
2322     impl<'a> Rewrite for GenericsArg<'a> {
2323         fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2324             match *self {
2325                 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2326                 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2327             }
2328         }
2329     }
2330     impl<'a> Spanned for GenericsArg<'a> {
2331         fn span(&self) -> Span {
2332             match *self {
2333                 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2334                 GenericsArg::TyParam(ref ty) => ty.span(),
2335             }
2336         }
2337     }
2338
2339     if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2340         return Some(String::new());
2341     }
2342
2343     let generics_args = generics
2344         .lifetimes
2345         .iter()
2346         .map(|lt| GenericsArg::Lifetime(lt))
2347         .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2348     let items = itemize_list(
2349         context.codemap,
2350         generics_args,
2351         ">",
2352         |arg| arg.span().lo(),
2353         |arg| arg.span().hi(),
2354         |arg| arg.rewrite(context, shape),
2355         context.codemap.span_after(span, "<"),
2356         span.hi(),
2357         false,
2358     );
2359     format_generics_item_list(context, items, shape, one_line_width)
2360 }
2361
2362 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2363     match config.generics_indent() {
2364         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2365         IndentStyle::Block => {
2366             // 1 = ","
2367             shape
2368                 .block()
2369                 .block_indent(config.tab_spaces())
2370                 .with_max_width(config)
2371                 .sub_width(1)
2372         }
2373     }
2374 }
2375
2376 pub fn format_generics_item_list<I>(
2377     context: &RewriteContext,
2378     items: I,
2379     shape: Shape,
2380     one_line_budget: usize,
2381 ) -> Option<String>
2382 where
2383     I: Iterator<Item = ListItem>,
2384 {
2385     let item_vec = items.collect::<Vec<_>>();
2386
2387     let tactic = definitive_tactic(
2388         &item_vec,
2389         ListTactic::HorizontalVertical,
2390         Separator::Comma,
2391         one_line_budget,
2392     );
2393     let fmt = ListFormatting {
2394         tactic: tactic,
2395         separator: ",",
2396         trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2397             SeparatorTactic::Never
2398         } else {
2399             context.config.trailing_comma()
2400         },
2401         separator_place: SeparatorPlace::Back,
2402         shape: shape,
2403         ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2404         preserve_newline: true,
2405         config: context.config,
2406     };
2407
2408     let list_str = try_opt!(write_list(&item_vec, &fmt));
2409
2410     Some(wrap_generics_with_angle_brackets(
2411         context,
2412         &list_str,
2413         shape.indent,
2414     ))
2415 }
2416
2417 pub fn wrap_generics_with_angle_brackets(
2418     context: &RewriteContext,
2419     list_str: &str,
2420     list_offset: Indent,
2421 ) -> String {
2422     if context.config.generics_indent() == IndentStyle::Block
2423         && (list_str.contains('\n') || list_str.ends_with(','))
2424     {
2425         format!(
2426             "<\n{}{}\n{}>",
2427             list_offset.to_string(context.config),
2428             list_str,
2429             list_offset
2430                 .block_unindent(context.config)
2431                 .to_string(context.config)
2432         )
2433     } else if context.config.spaces_within_angle_brackets() {
2434         format!("< {} >", list_str)
2435     } else {
2436         format!("<{}>", list_str)
2437     }
2438 }
2439
2440 fn rewrite_trait_bounds(
2441     context: &RewriteContext,
2442     type_param_bounds: &ast::TyParamBounds,
2443     shape: Shape,
2444 ) -> Option<String> {
2445     let bounds: &[_] = type_param_bounds;
2446
2447     if bounds.is_empty() {
2448         return Some(String::new());
2449     }
2450     let bound_str = try_opt!(
2451         bounds
2452             .iter()
2453             .map(|ty_bound| ty_bound.rewrite(context, shape))
2454             .collect::<Option<Vec<_>>>()
2455     );
2456     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2457 }
2458
2459 fn rewrite_where_clause_rfc_style(
2460     context: &RewriteContext,
2461     where_clause: &ast::WhereClause,
2462     shape: Shape,
2463     terminator: &str,
2464     span_end: Option<BytePos>,
2465     span_end_before_where: BytePos,
2466     where_clause_option: WhereClauseOption,
2467 ) -> Option<String> {
2468     let block_shape = shape.block().with_max_width(context.config);
2469
2470     let (span_before, span_after) =
2471         missing_span_before_after_where(span_end_before_where, where_clause);
2472     let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2473         context,
2474         span_before,
2475         span_after,
2476         shape,
2477     ));
2478
2479     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2480         " ".to_owned()
2481     } else {
2482         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2483     };
2484
2485     let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2486     // each clause on one line, trailing comma (except if suppress_comma)
2487     let span_start = where_clause.predicates[0].span().lo();
2488     // If we don't have the start of the next span, then use the end of the
2489     // predicates, but that means we miss comments.
2490     let len = where_clause.predicates.len();
2491     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2492     let span_end = span_end.unwrap_or(end_of_preds);
2493     let items = itemize_list(
2494         context.codemap,
2495         where_clause.predicates.iter(),
2496         terminator,
2497         |pred| pred.span().lo(),
2498         |pred| pred.span().hi(),
2499         |pred| pred.rewrite(context, block_shape),
2500         span_start,
2501         span_end,
2502         false,
2503     );
2504     let comma_tactic = if where_clause_option.suppress_comma {
2505         SeparatorTactic::Never
2506     } else {
2507         context.config.trailing_comma()
2508     };
2509
2510     let fmt = ListFormatting {
2511         tactic: DefinitiveListTactic::Vertical,
2512         separator: ",",
2513         trailing_separator: comma_tactic,
2514         separator_place: SeparatorPlace::Back,
2515         shape: clause_shape,
2516         ends_with_newline: true,
2517         preserve_newline: true,
2518         config: context.config,
2519     };
2520     let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2521
2522     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2523         String::new()
2524     } else {
2525         format!("\n{}", shape.indent.to_string(context.config))
2526     };
2527     let newline_before_where = comment_separator(&comment_before, shape);
2528     let newline_after_where = comment_separator(&comment_after, clause_shape);
2529
2530     // 6 = `where `
2531     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2532         && comment_after.is_empty() && !preds_str.contains('\n')
2533         && 6 + preds_str.len() <= shape.width
2534     {
2535         String::from(" ")
2536     } else {
2537         format!("\n{}", clause_shape.indent.to_string(context.config))
2538     };
2539     Some(format!(
2540         "{}{}{}where{}{}{}{}",
2541         starting_newline,
2542         comment_before,
2543         newline_before_where,
2544         newline_after_where,
2545         comment_after,
2546         clause_sep,
2547         preds_str
2548     ))
2549 }
2550
2551 fn rewrite_where_clause(
2552     context: &RewriteContext,
2553     where_clause: &ast::WhereClause,
2554     brace_style: BraceStyle,
2555     shape: Shape,
2556     density: Density,
2557     terminator: &str,
2558     span_end: Option<BytePos>,
2559     span_end_before_where: BytePos,
2560     where_clause_option: WhereClauseOption,
2561 ) -> Option<String> {
2562     if where_clause.predicates.is_empty() {
2563         return Some(String::new());
2564     }
2565
2566     if context.config.where_style() == Style::Rfc {
2567         return rewrite_where_clause_rfc_style(
2568             context,
2569             where_clause,
2570             shape,
2571             terminator,
2572             span_end,
2573             span_end_before_where,
2574             where_clause_option,
2575         );
2576     }
2577
2578     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2579
2580     let offset = match context.config.where_pred_indent() {
2581         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2582         // 6 = "where ".len()
2583         IndentStyle::Visual => shape.indent + extra_indent + 6,
2584     };
2585     // FIXME: if where_pred_indent != Visual, then the budgets below might
2586     // be out by a char or two.
2587
2588     let budget = context.config.max_width() - offset.width();
2589     let span_start = where_clause.predicates[0].span().lo();
2590     // If we don't have the start of the next span, then use the end of the
2591     // predicates, but that means we miss comments.
2592     let len = where_clause.predicates.len();
2593     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2594     let span_end = span_end.unwrap_or(end_of_preds);
2595     let items = itemize_list(
2596         context.codemap,
2597         where_clause.predicates.iter(),
2598         terminator,
2599         |pred| pred.span().lo(),
2600         |pred| pred.span().hi(),
2601         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2602         span_start,
2603         span_end,
2604         false,
2605     );
2606     let item_vec = items.collect::<Vec<_>>();
2607     // FIXME: we don't need to collect here if the where_layout isn't
2608     // HorizontalVertical.
2609     let tactic = definitive_tactic(
2610         &item_vec,
2611         context.config.where_layout(),
2612         Separator::Comma,
2613         budget,
2614     );
2615
2616     let mut comma_tactic = context.config.trailing_comma();
2617     // Kind of a hack because we don't usually have trailing commas in where clauses.
2618     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2619         comma_tactic = SeparatorTactic::Never;
2620     }
2621
2622     let fmt = ListFormatting {
2623         tactic: tactic,
2624         separator: ",",
2625         trailing_separator: comma_tactic,
2626         separator_place: SeparatorPlace::Back,
2627         shape: Shape::legacy(budget, offset),
2628         ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2629         preserve_newline: true,
2630         config: context.config,
2631     };
2632     let preds_str = try_opt!(write_list(&item_vec, &fmt));
2633
2634     let end_length = if terminator == "{" {
2635         // If the brace is on the next line we don't need to count it otherwise it needs two
2636         // characters " {"
2637         match brace_style {
2638             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2639             BraceStyle::PreferSameLine => 2,
2640         }
2641     } else if terminator == "=" {
2642         2
2643     } else {
2644         terminator.len()
2645     };
2646     if density == Density::Tall || preds_str.contains('\n')
2647         || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2648     {
2649         Some(format!(
2650             "\n{}where {}",
2651             (shape.indent + extra_indent).to_string(context.config),
2652             preds_str
2653         ))
2654     } else {
2655         Some(format!(" where {}", preds_str))
2656     }
2657 }
2658
2659 fn missing_span_before_after_where(
2660     before_item_span_end: BytePos,
2661     where_clause: &ast::WhereClause,
2662 ) -> (Span, Span) {
2663     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2664     // 5 = `where`
2665     let pos_after_where = where_clause.span.lo() + BytePos(5);
2666     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2667     (missing_span_before, missing_span_after)
2668 }
2669
2670 fn rewrite_comments_before_after_where(
2671     context: &RewriteContext,
2672     span_before_where: Span,
2673     span_after_where: Span,
2674     shape: Shape,
2675 ) -> Option<(String, String)> {
2676     let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2677     let after_comment = try_opt!(rewrite_missing_comment(
2678         span_after_where,
2679         shape.block_indent(context.config.tab_spaces()),
2680         context,
2681     ));
2682     Some((before_comment, after_comment))
2683 }
2684
2685 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2686     format!("{}{}{}", format_visibility(vis), item_name, ident)
2687 }
2688
2689 fn format_generics(
2690     context: &RewriteContext,
2691     generics: &ast::Generics,
2692     opener: &str,
2693     terminator: &str,
2694     brace_style: BraceStyle,
2695     force_same_line_brace: bool,
2696     offset: Indent,
2697     span: Span,
2698     used_width: usize,
2699 ) -> Option<String> {
2700     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2701     let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2702
2703     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2704         let budget = context.budget(last_line_used_width(&result, offset.width()));
2705         let option = WhereClauseOption::snuggled(&result);
2706         let where_clause_str = try_opt!(rewrite_where_clause(
2707             context,
2708             &generics.where_clause,
2709             brace_style,
2710             Shape::legacy(budget, offset.block_only()),
2711             Density::Tall,
2712             terminator,
2713             Some(span.hi()),
2714             generics.span.hi(),
2715             option,
2716         ));
2717         result.push_str(&where_clause_str);
2718         force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2719             || (generics.where_clause.predicates.is_empty()
2720                 && trimmed_last_line_width(&result) == 1)
2721     } else {
2722         force_same_line_brace || trimmed_last_line_width(&result) == 1
2723             || brace_style != BraceStyle::AlwaysNextLine
2724     };
2725     let total_used_width = last_line_used_width(&result, used_width);
2726     let remaining_budget = context.budget(total_used_width);
2727     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2728     // and hence we take the closer into account as well for one line budget.
2729     // We assume that the closer has the same length as the opener.
2730     let overhead = if force_same_line_brace {
2731         1 + opener.len() + opener.len()
2732     } else {
2733         1 + opener.len()
2734     };
2735     let forbid_same_line_brace = overhead > remaining_budget;
2736     if !forbid_same_line_brace && same_line_brace {
2737         result.push(' ');
2738     } else {
2739         result.push('\n');
2740         result.push_str(&offset.block_only().to_string(context.config));
2741     }
2742     result.push_str(opener);
2743
2744     Some(result)
2745 }
2746
2747 impl Rewrite for ast::ForeignItem {
2748     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2749         let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2750         // Drop semicolon or it will be interpreted as comment.
2751         // FIXME: this may be a faulty span from libsyntax.
2752         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2753
2754         let item_str = try_opt!(match self.node {
2755             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2756                 rewrite_fn_base(
2757                     context,
2758                     shape.indent,
2759                     self.ident,
2760                     fn_decl,
2761                     generics,
2762                     ast::Unsafety::Normal,
2763                     ast::Constness::NotConst,
2764                     ast::Defaultness::Final,
2765                     // These are not actually rust functions,
2766                     // but we format them as such.
2767                     abi::Abi::Rust,
2768                     &self.vis,
2769                     span,
2770                     false,
2771                     false,
2772                     false,
2773                 ).map(|(s, _)| format!("{};", s))
2774             }
2775             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2776                 // FIXME(#21): we're dropping potential comments in between the
2777                 // function keywords here.
2778                 let vis = format_visibility(&self.vis);
2779                 let mut_str = if is_mutable { "mut " } else { "" };
2780                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2781                 // 1 = ;
2782                 let shape = try_opt!(shape.sub_width(1));
2783                 ty.rewrite(context, shape).map(|ty_str| {
2784                     // 1 = space between prefix and type.
2785                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2786                         String::from(" ")
2787                     } else {
2788                         let nested_indent = shape.indent.block_indent(context.config);
2789                         format!("\n{}", nested_indent.to_string(context.config))
2790                     };
2791                     format!("{}{}{};", prefix, sep, ty_str)
2792                 })
2793             }
2794         });
2795
2796         let missing_span = if self.attrs.is_empty() {
2797             mk_sp(self.span.lo(), self.span.lo())
2798         } else {
2799             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2800         };
2801         combine_strs_with_missing_comments(
2802             context,
2803             &attrs_str,
2804             &item_str,
2805             missing_span,
2806             shape,
2807             false,
2808         )
2809     }
2810 }