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