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