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