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