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