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