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