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