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