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