]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Merge pull request #3838 from calebcartwright/static-raw-ident-prefix
[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 = generics_shape_from_config(
806             context.config,
807             Shape::indented(offset + last_line_width(&result), context.config),
808             0,
809         )?;
810         let generics_str = rewrite_generics(context, "impl", generics, shape)?;
811         result.push_str(&generics_str);
812
813         let polarity_str = if polarity == ast::ImplPolarity::Negative {
814             "!"
815         } else {
816             ""
817         };
818
819         if let Some(ref trait_ref) = *trait_ref {
820             let result_len = last_line_width(&result);
821             result.push_str(&rewrite_trait_ref(
822                 context,
823                 trait_ref,
824                 offset,
825                 polarity_str,
826                 result_len,
827             )?);
828         }
829
830         // Try to put the self type in a single line.
831         // ` for`
832         let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
833         let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
834             // If there is no where-clause adapt budget for type formatting to take space and curly
835             // brace into account.
836             match context.config.brace_style() {
837                 BraceStyle::AlwaysNextLine => 0,
838                 _ => 2,
839             }
840         } else {
841             0
842         };
843         let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
844         // 1 = space before the type.
845         let budget = context.budget(used_space + 1);
846         if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
847             if !self_ty_str.contains('\n') {
848                 if trait_ref.is_some() {
849                     result.push_str(" for ");
850                 } else {
851                     result.push(' ');
852                 }
853                 result.push_str(&self_ty_str);
854                 return Some(result);
855             }
856         }
857
858         // Couldn't fit the self type on a single line, put it on a new line.
859         result.push('\n');
860         // Add indentation of one additional tab.
861         let new_line_offset = offset.block_indent(context.config);
862         result.push_str(&new_line_offset.to_string(context.config));
863         if trait_ref.is_some() {
864             result.push_str("for ");
865         }
866         let budget = context.budget(last_line_width(&result));
867         let type_offset = match context.config.indent_style() {
868             IndentStyle::Visual => new_line_offset + trait_ref_overhead,
869             IndentStyle::Block => new_line_offset,
870         };
871         result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
872         Some(result)
873     } else {
874         unreachable!();
875     }
876 }
877
878 fn rewrite_trait_ref(
879     context: &RewriteContext<'_>,
880     trait_ref: &ast::TraitRef,
881     offset: Indent,
882     polarity_str: &str,
883     result_len: usize,
884 ) -> Option<String> {
885     // 1 = space between generics and trait_ref
886     let used_space = 1 + polarity_str.len() + result_len;
887     let shape = Shape::indented(offset + used_space, context.config);
888     if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
889         if !trait_ref_str.contains('\n') {
890             return Some(format!(" {}{}", polarity_str, trait_ref_str));
891         }
892     }
893     // We could not make enough space for trait_ref, so put it on new line.
894     let offset = offset.block_indent(context.config);
895     let shape = Shape::indented(offset, context.config);
896     let trait_ref_str = trait_ref.rewrite(context, shape)?;
897     Some(format!(
898         "{}{}{}",
899         offset.to_string_with_newline(context.config),
900         polarity_str,
901         trait_ref_str
902     ))
903 }
904
905 pub(crate) struct StructParts<'a> {
906     prefix: &'a str,
907     ident: ast::Ident,
908     vis: &'a ast::Visibility,
909     def: &'a ast::VariantData,
910     generics: Option<&'a ast::Generics>,
911     span: Span,
912 }
913
914 impl<'a> StructParts<'a> {
915     fn format_header(&self, context: &RewriteContext<'_>) -> String {
916         format_header(context, self.prefix, self.ident, self.vis)
917     }
918
919     fn from_variant(variant: &'a ast::Variant) -> Self {
920         StructParts {
921             prefix: "",
922             ident: variant.ident,
923             vis: &DEFAULT_VISIBILITY,
924             def: &variant.data,
925             generics: None,
926             span: variant.span,
927         }
928     }
929
930     pub(crate) fn from_item(item: &'a ast::Item) -> Self {
931         let (prefix, def, generics) = match item.kind {
932             ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
933             ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
934             _ => unreachable!(),
935         };
936         StructParts {
937             prefix,
938             ident: item.ident,
939             vis: &item.vis,
940             def,
941             generics: Some(generics),
942             span: item.span,
943         }
944     }
945 }
946
947 fn format_struct(
948     context: &RewriteContext<'_>,
949     struct_parts: &StructParts<'_>,
950     offset: Indent,
951     one_line_width: Option<usize>,
952 ) -> Option<String> {
953     match *struct_parts.def {
954         ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
955         ast::VariantData::Tuple(ref fields, _) => {
956             format_tuple_struct(context, struct_parts, fields, offset)
957         }
958         ast::VariantData::Struct(ref fields, _) => {
959             format_struct_struct(context, struct_parts, fields, offset, one_line_width)
960         }
961     }
962 }
963
964 pub(crate) fn format_trait(
965     context: &RewriteContext<'_>,
966     item: &ast::Item,
967     offset: Indent,
968 ) -> Option<String> {
969     if let ast::ItemKind::Trait(
970         is_auto,
971         unsafety,
972         ref generics,
973         ref generic_bounds,
974         ref trait_items,
975     ) = item.kind
976     {
977         let mut result = String::with_capacity(128);
978         let header = format!(
979             "{}{}{}trait ",
980             format_visibility(context, &item.vis),
981             format_unsafety(unsafety),
982             format_auto(is_auto),
983         );
984         result.push_str(&header);
985
986         let body_lo = context.snippet_provider.span_after(item.span, "{");
987
988         let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
989         let generics_str =
990             rewrite_generics(context, rewrite_ident(context, item.ident), generics, shape)?;
991         result.push_str(&generics_str);
992
993         // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
994         if !generic_bounds.is_empty() {
995             let ident_hi = context
996                 .snippet_provider
997                 .span_after(item.span, &item.ident.as_str());
998             let bound_hi = generic_bounds.last().unwrap().span().hi();
999             let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1000             if contains_comment(snippet) {
1001                 return None;
1002             }
1003
1004             result = rewrite_assign_rhs_with(
1005                 context,
1006                 result + ":",
1007                 generic_bounds,
1008                 shape,
1009                 RhsTactics::ForceNextLineWithoutIndent,
1010             )?;
1011         }
1012
1013         // Rewrite where-clause.
1014         if !generics.where_clause.predicates.is_empty() {
1015             let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1016
1017             let where_budget = context.budget(last_line_width(&result));
1018             let pos_before_where = if generic_bounds.is_empty() {
1019                 generics.where_clause.span.lo()
1020             } else {
1021                 generic_bounds[generic_bounds.len() - 1].span().hi()
1022             };
1023             let option = WhereClauseOption::snuggled(&generics_str);
1024             let where_clause_str = rewrite_where_clause(
1025                 context,
1026                 &generics.where_clause,
1027                 context.config.brace_style(),
1028                 Shape::legacy(where_budget, offset.block_only()),
1029                 where_on_new_line,
1030                 "{",
1031                 None,
1032                 pos_before_where,
1033                 option,
1034             )?;
1035             // If the where-clause cannot fit on the same line,
1036             // put the where-clause on a new line
1037             if !where_clause_str.contains('\n')
1038                 && last_line_width(&result) + where_clause_str.len() + offset.width()
1039                     > context.config.comment_width()
1040             {
1041                 let width = offset.block_indent + context.config.tab_spaces() - 1;
1042                 let where_indent = Indent::new(0, width);
1043                 result.push_str(&where_indent.to_string_with_newline(context.config));
1044             }
1045             result.push_str(&where_clause_str);
1046         } else {
1047             let item_snippet = context.snippet(item.span);
1048             if let Some(lo) = item_snippet.find('/') {
1049                 // 1 = `{`
1050                 let comment_hi = body_lo - BytePos(1);
1051                 let comment_lo = item.span.lo() + BytePos(lo as u32);
1052                 if comment_lo < comment_hi {
1053                     match recover_missing_comment_in_span(
1054                         mk_sp(comment_lo, comment_hi),
1055                         Shape::indented(offset, context.config),
1056                         context,
1057                         last_line_width(&result),
1058                     ) {
1059                         Some(ref missing_comment) if !missing_comment.is_empty() => {
1060                             result.push_str(missing_comment);
1061                         }
1062                         _ => (),
1063                     }
1064                 }
1065             }
1066         }
1067
1068         match context.config.brace_style() {
1069             _ if last_line_contains_single_line_comment(&result)
1070                 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1071             {
1072                 result.push_str(&offset.to_string_with_newline(context.config));
1073             }
1074             BraceStyle::AlwaysNextLine => {
1075                 result.push_str(&offset.to_string_with_newline(context.config));
1076             }
1077             BraceStyle::PreferSameLine => result.push(' '),
1078             BraceStyle::SameLineWhere => {
1079                 if result.contains('\n')
1080                     || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1081                 {
1082                     result.push_str(&offset.to_string_with_newline(context.config));
1083                 } else {
1084                     result.push(' ');
1085                 }
1086             }
1087         }
1088         result.push('{');
1089
1090         let snippet = context.snippet(item.span);
1091         let open_pos = snippet.find_uncommented("{")? + 1;
1092         let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1093
1094         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1095             let mut visitor = FmtVisitor::from_context(context);
1096             visitor.block_indent = offset.block_only().block_indent(context.config);
1097             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1098
1099             for item in trait_items {
1100                 visitor.visit_trait_item(item);
1101             }
1102
1103             visitor.format_missing(item.span.hi() - BytePos(1));
1104
1105             let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1106
1107             result.push_str(&inner_indent_str);
1108             result.push_str(visitor.buffer.trim());
1109             result.push_str(&outer_indent_str);
1110         } else if result.contains('\n') {
1111             result.push_str(&outer_indent_str);
1112         }
1113
1114         result.push('}');
1115         Some(result)
1116     } else {
1117         unreachable!();
1118     }
1119 }
1120
1121 struct OpaqueTypeBounds<'a> {
1122     generic_bounds: &'a ast::GenericBounds,
1123 }
1124
1125 impl<'a> Rewrite for OpaqueTypeBounds<'a> {
1126     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1127         self.generic_bounds
1128             .rewrite(context, shape)
1129             .map(|s| format!("impl {}", s))
1130     }
1131 }
1132
1133 pub(crate) struct TraitAliasBounds<'a> {
1134     generic_bounds: &'a ast::GenericBounds,
1135     generics: &'a ast::Generics,
1136 }
1137
1138 impl<'a> Rewrite for TraitAliasBounds<'a> {
1139     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1140         let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
1141
1142         let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1143         option.allow_single_line();
1144
1145         let where_str = rewrite_where_clause(
1146             context,
1147             &self.generics.where_clause,
1148             context.config.brace_style(),
1149             shape,
1150             false,
1151             ";",
1152             None,
1153             self.generics.where_clause.span.lo(),
1154             option,
1155         )?;
1156
1157         let fits_single_line = !generic_bounds_str.contains('\n')
1158             && !where_str.contains('\n')
1159             && generic_bounds_str.len() + where_str.len() + 1 <= shape.width;
1160         let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1161             Cow::from("")
1162         } else if fits_single_line {
1163             Cow::from(" ")
1164         } else {
1165             shape.indent.to_string_with_newline(&context.config)
1166         };
1167
1168         Some(format!("{}{}{}", generic_bounds_str, space, where_str))
1169     }
1170 }
1171
1172 pub(crate) fn format_trait_alias(
1173     context: &RewriteContext<'_>,
1174     ident: ast::Ident,
1175     vis: &ast::Visibility,
1176     generics: &ast::Generics,
1177     generic_bounds: &ast::GenericBounds,
1178     shape: Shape,
1179 ) -> Option<String> {
1180     let alias = rewrite_ident(context, ident);
1181     // 6 = "trait ", 2 = " ="
1182     let g_shape = shape.offset_left(6)?.sub_width(2)?;
1183     let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
1184     let vis_str = format_visibility(context, vis);
1185     let lhs = format!("{}trait {} =", vis_str, generics_str);
1186     // 1 = ";"
1187     let trait_alias_bounds = TraitAliasBounds {
1188         generics,
1189         generic_bounds,
1190     };
1191     rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";")
1192 }
1193
1194 fn format_unit_struct(
1195     context: &RewriteContext<'_>,
1196     p: &StructParts<'_>,
1197     offset: Indent,
1198 ) -> Option<String> {
1199     let header_str = format_header(context, p.prefix, p.ident, p.vis);
1200     let generics_str = if let Some(generics) = p.generics {
1201         let hi = context.snippet_provider.span_before(p.span, ";");
1202         format_generics(
1203             context,
1204             generics,
1205             context.config.brace_style(),
1206             BracePos::None,
1207             offset,
1208             // make a span that starts right after `struct Foo`
1209             mk_sp(p.ident.span.hi(), hi),
1210             last_line_width(&header_str),
1211         )?
1212     } else {
1213         String::new()
1214     };
1215     Some(format!("{}{};", header_str, generics_str))
1216 }
1217
1218 pub(crate) fn format_struct_struct(
1219     context: &RewriteContext<'_>,
1220     struct_parts: &StructParts<'_>,
1221     fields: &[ast::StructField],
1222     offset: Indent,
1223     one_line_width: Option<usize>,
1224 ) -> Option<String> {
1225     let mut result = String::with_capacity(1024);
1226     let span = struct_parts.span;
1227
1228     let header_str = struct_parts.format_header(context);
1229     result.push_str(&header_str);
1230
1231     let header_hi = struct_parts.ident.span.hi();
1232     let body_lo = context.snippet_provider.span_after(span, "{");
1233
1234     let generics_str = match struct_parts.generics {
1235         Some(g) => format_generics(
1236             context,
1237             g,
1238             context.config.brace_style(),
1239             if fields.is_empty() {
1240                 BracePos::ForceSameLine
1241             } else {
1242                 BracePos::Auto
1243             },
1244             offset,
1245             // make a span that starts right after `struct Foo`
1246             mk_sp(header_hi, body_lo),
1247             last_line_width(&result),
1248         )?,
1249         None => {
1250             // 3 = ` {}`, 2 = ` {`.
1251             let overhead = if fields.is_empty() { 3 } else { 2 };
1252             if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1253                 || context.config.max_width() < overhead + result.len()
1254             {
1255                 format!("\n{}{{", offset.block_only().to_string(context.config))
1256             } else {
1257                 " {".to_owned()
1258             }
1259         }
1260     };
1261     // 1 = `}`
1262     let overhead = if fields.is_empty() { 1 } else { 0 };
1263     let total_width = result.len() + generics_str.len() + overhead;
1264     if !generics_str.is_empty()
1265         && !generics_str.contains('\n')
1266         && total_width > context.config.max_width()
1267     {
1268         result.push('\n');
1269         result.push_str(&offset.to_string(context.config));
1270         result.push_str(generics_str.trim_start());
1271     } else {
1272         result.push_str(&generics_str);
1273     }
1274
1275     if fields.is_empty() {
1276         let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1277         format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1278         return Some(result);
1279     }
1280
1281     // 3 = ` ` and ` }`
1282     let one_line_budget = context.budget(result.len() + 3 + offset.width());
1283     let one_line_budget =
1284         one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1285
1286     let items_str = rewrite_with_alignment(
1287         fields,
1288         context,
1289         Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
1290         mk_sp(body_lo, span.hi()),
1291         one_line_budget,
1292     )?;
1293
1294     if !items_str.contains('\n')
1295         && !result.contains('\n')
1296         && items_str.len() <= one_line_budget
1297         && !last_line_contains_single_line_comment(&items_str)
1298     {
1299         Some(format!("{} {} }}", result, items_str))
1300     } else {
1301         Some(format!(
1302             "{}\n{}{}\n{}}}",
1303             result,
1304             offset
1305                 .block_indent(context.config)
1306                 .to_string(context.config),
1307             items_str,
1308             offset.to_string(context.config)
1309         ))
1310     }
1311 }
1312
1313 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1314     match vis.node {
1315         ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1316         _ => default_span.lo(),
1317     }
1318 }
1319
1320 // Format tuple or struct without any fields. We need to make sure that the comments
1321 // inside the delimiters are preserved.
1322 fn format_empty_struct_or_tuple(
1323     context: &RewriteContext<'_>,
1324     span: Span,
1325     offset: Indent,
1326     result: &mut String,
1327     opener: &str,
1328     closer: &str,
1329 ) {
1330     // 3 = " {}" or "();"
1331     let used_width = last_line_used_width(&result, offset.width()) + 3;
1332     if used_width > context.config.max_width() {
1333         result.push_str(&offset.to_string_with_newline(context.config))
1334     }
1335     result.push_str(opener);
1336     match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1337         Some(ref s) if s.is_empty() => (),
1338         Some(ref s) => {
1339             if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1340                 let nested_indent_str = offset
1341                     .block_indent(context.config)
1342                     .to_string_with_newline(context.config);
1343                 result.push_str(&nested_indent_str);
1344             }
1345             result.push_str(s);
1346             if last_line_contains_single_line_comment(s) {
1347                 result.push_str(&offset.to_string_with_newline(context.config));
1348             }
1349         }
1350         None => result.push_str(context.snippet(span)),
1351     }
1352     result.push_str(closer);
1353 }
1354
1355 fn format_tuple_struct(
1356     context: &RewriteContext<'_>,
1357     struct_parts: &StructParts<'_>,
1358     fields: &[ast::StructField],
1359     offset: Indent,
1360 ) -> Option<String> {
1361     let mut result = String::with_capacity(1024);
1362     let span = struct_parts.span;
1363
1364     let header_str = struct_parts.format_header(context);
1365     result.push_str(&header_str);
1366
1367     let body_lo = if fields.is_empty() {
1368         let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1369         context
1370             .snippet_provider
1371             .span_after(mk_sp(lo, span.hi()), "(")
1372     } else {
1373         fields[0].span.lo()
1374     };
1375     let body_hi = if fields.is_empty() {
1376         context
1377             .snippet_provider
1378             .span_after(mk_sp(body_lo, span.hi()), ")")
1379     } else {
1380         // This is a dirty hack to work around a missing `)` from the span of the last field.
1381         let last_arg_span = fields[fields.len() - 1].span;
1382         context
1383             .snippet_provider
1384             .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1385             .unwrap_or_else(|| last_arg_span.hi())
1386     };
1387
1388     let where_clause_str = match struct_parts.generics {
1389         Some(generics) => {
1390             let budget = context.budget(last_line_width(&header_str));
1391             let shape = Shape::legacy(budget, offset);
1392             let generics_str = rewrite_generics(context, "", generics, shape)?;
1393             result.push_str(&generics_str);
1394
1395             let where_budget = context.budget(last_line_width(&result));
1396             let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1397             rewrite_where_clause(
1398                 context,
1399                 &generics.where_clause,
1400                 context.config.brace_style(),
1401                 Shape::legacy(where_budget, offset.block_only()),
1402                 false,
1403                 ";",
1404                 None,
1405                 body_hi,
1406                 option,
1407             )?
1408         }
1409         None => "".to_owned(),
1410     };
1411
1412     if fields.is_empty() {
1413         let body_hi = context
1414             .snippet_provider
1415             .span_before(mk_sp(body_lo, span.hi()), ")");
1416         let inner_span = mk_sp(body_lo, body_hi);
1417         format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1418     } else {
1419         let shape = Shape::indented(offset, context.config).sub_width(1)?;
1420         result = overflow::rewrite_with_parens(
1421             context,
1422             &result,
1423             fields.iter(),
1424             shape,
1425             span,
1426             context.config.width_heuristics().fn_call_width,
1427             None,
1428         )?;
1429     }
1430
1431     if !where_clause_str.is_empty()
1432         && !where_clause_str.contains('\n')
1433         && (result.contains('\n')
1434             || offset.block_indent + result.len() + where_clause_str.len() + 1
1435                 > context.config.max_width())
1436     {
1437         // We need to put the where-clause on a new line, but we didn't
1438         // know that earlier, so the where-clause will not be indented properly.
1439         result.push('\n');
1440         result.push_str(
1441             &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1442         );
1443     }
1444     result.push_str(&where_clause_str);
1445
1446     Some(result)
1447 }
1448
1449 fn rewrite_type_prefix(
1450     context: &RewriteContext<'_>,
1451     indent: Indent,
1452     prefix: &str,
1453     ident: ast::Ident,
1454     generics: &ast::Generics,
1455 ) -> Option<String> {
1456     let mut result = String::with_capacity(128);
1457     result.push_str(prefix);
1458     let ident_str = rewrite_ident(context, ident);
1459
1460     // 2 = `= `
1461     if generics.params.is_empty() {
1462         result.push_str(ident_str)
1463     } else {
1464         let g_shape = Shape::indented(indent, context.config)
1465             .offset_left(result.len())?
1466             .sub_width(2)?;
1467         let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1468         result.push_str(&generics_str);
1469     }
1470
1471     let where_budget = context.budget(last_line_width(&result));
1472     let option = WhereClauseOption::snuggled(&result);
1473     let where_clause_str = rewrite_where_clause(
1474         context,
1475         &generics.where_clause,
1476         context.config.brace_style(),
1477         Shape::legacy(where_budget, indent),
1478         false,
1479         "=",
1480         None,
1481         generics.span.hi(),
1482         option,
1483     )?;
1484     result.push_str(&where_clause_str);
1485
1486     Some(result)
1487 }
1488
1489 fn rewrite_type_item<R: Rewrite>(
1490     context: &RewriteContext<'_>,
1491     indent: Indent,
1492     prefix: &str,
1493     suffix: &str,
1494     ident: ast::Ident,
1495     rhs: &R,
1496     generics: &ast::Generics,
1497     vis: &ast::Visibility,
1498 ) -> Option<String> {
1499     let mut result = String::with_capacity(128);
1500     result.push_str(&rewrite_type_prefix(
1501         context,
1502         indent,
1503         &format!("{}{} ", format_visibility(context, vis), prefix),
1504         ident,
1505         generics,
1506     )?);
1507
1508     if generics.where_clause.predicates.is_empty() {
1509         result.push_str(suffix);
1510     } else {
1511         result.push_str(&indent.to_string_with_newline(context.config));
1512         result.push_str(suffix.trim_start());
1513     }
1514
1515     // 1 = ";"
1516     let rhs_shape = Shape::indented(indent, context.config).sub_width(1)?;
1517     rewrite_assign_rhs(context, result, rhs, rhs_shape).map(|s| s + ";")
1518 }
1519
1520 pub(crate) fn rewrite_type_alias(
1521     context: &RewriteContext<'_>,
1522     indent: Indent,
1523     ident: ast::Ident,
1524     ty: &ast::Ty,
1525     generics: &ast::Generics,
1526     vis: &ast::Visibility,
1527 ) -> Option<String> {
1528     rewrite_type_item(context, indent, "type", " =", ident, ty, generics, vis)
1529 }
1530
1531 pub(crate) fn rewrite_opaque_type(
1532     context: &RewriteContext<'_>,
1533     indent: Indent,
1534     ident: ast::Ident,
1535     generic_bounds: &ast::GenericBounds,
1536     generics: &ast::Generics,
1537     vis: &ast::Visibility,
1538 ) -> Option<String> {
1539     let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
1540     rewrite_type_item(
1541         context,
1542         indent,
1543         "type",
1544         " =",
1545         ident,
1546         &opaque_type_bounds,
1547         generics,
1548         vis,
1549     )
1550 }
1551
1552 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1553     (
1554         if config.space_before_colon() { " " } else { "" },
1555         if config.space_after_colon() { " " } else { "" },
1556     )
1557 }
1558
1559 pub(crate) fn rewrite_struct_field_prefix(
1560     context: &RewriteContext<'_>,
1561     field: &ast::StructField,
1562 ) -> Option<String> {
1563     let vis = format_visibility(context, &field.vis);
1564     let type_annotation_spacing = type_annotation_spacing(context.config);
1565     Some(match field.ident {
1566         Some(name) => format!(
1567             "{}{}{}:",
1568             vis,
1569             rewrite_ident(context, name),
1570             type_annotation_spacing.0
1571         ),
1572         None => vis.to_string(),
1573     })
1574 }
1575
1576 impl Rewrite for ast::StructField {
1577     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1578         rewrite_struct_field(context, self, shape, 0)
1579     }
1580 }
1581
1582 pub(crate) fn rewrite_struct_field(
1583     context: &RewriteContext<'_>,
1584     field: &ast::StructField,
1585     shape: Shape,
1586     lhs_max_width: usize,
1587 ) -> Option<String> {
1588     if contains_skip(&field.attrs) {
1589         return Some(context.snippet(field.span()).to_owned());
1590     }
1591
1592     let type_annotation_spacing = type_annotation_spacing(context.config);
1593     let prefix = rewrite_struct_field_prefix(context, field)?;
1594
1595     let attrs_str = field.attrs.rewrite(context, shape)?;
1596     let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1597     let missing_span = if field.attrs.is_empty() {
1598         mk_sp(field.span.lo(), field.span.lo())
1599     } else {
1600         mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1601     };
1602     let mut spacing = String::from(if field.ident.is_some() {
1603         type_annotation_spacing.1
1604     } else {
1605         ""
1606     });
1607     // Try to put everything on a single line.
1608     let attr_prefix = combine_strs_with_missing_comments(
1609         context,
1610         &attrs_str,
1611         &prefix,
1612         missing_span,
1613         shape,
1614         attrs_extendable,
1615     )?;
1616     let overhead = last_line_width(&attr_prefix);
1617     let lhs_offset = lhs_max_width.saturating_sub(overhead);
1618     for _ in 0..lhs_offset {
1619         spacing.push(' ');
1620     }
1621     // In this extreme case we will be missing a space between an attribute and a field.
1622     if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1623         spacing.push(' ');
1624     }
1625     let orig_ty = shape
1626         .offset_left(overhead + spacing.len())
1627         .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1628     if let Some(ref ty) = orig_ty {
1629         if !ty.contains('\n') {
1630             return Some(attr_prefix + &spacing + ty);
1631         }
1632     }
1633
1634     let is_prefix_empty = prefix.is_empty();
1635     // We must use multiline. We are going to put attributes and a field on different lines.
1636     let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1637     // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1638     let field_str = if is_prefix_empty {
1639         field_str.trim_start()
1640     } else {
1641         &field_str
1642     };
1643     combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1644 }
1645
1646 pub(crate) struct StaticParts<'a> {
1647     prefix: &'a str,
1648     vis: &'a ast::Visibility,
1649     ident: ast::Ident,
1650     ty: &'a ast::Ty,
1651     mutability: ast::Mutability,
1652     expr_opt: Option<&'a ptr::P<ast::Expr>>,
1653     defaultness: Option<ast::Defaultness>,
1654     span: Span,
1655 }
1656
1657 impl<'a> StaticParts<'a> {
1658     pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1659         let (prefix, ty, mutability, expr) = match item.kind {
1660             ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1661             ast::ItemKind::Const(ref ty, ref expr) => {
1662                 ("const", ty, ast::Mutability::Immutable, expr)
1663             }
1664             _ => unreachable!(),
1665         };
1666         StaticParts {
1667             prefix,
1668             vis: &item.vis,
1669             ident: item.ident,
1670             ty,
1671             mutability,
1672             expr_opt: Some(expr),
1673             defaultness: None,
1674             span: item.span,
1675         }
1676     }
1677
1678     pub(crate) fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1679         let (ty, expr_opt) = match ti.kind {
1680             ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1681             _ => unreachable!(),
1682         };
1683         StaticParts {
1684             prefix: "const",
1685             vis: &DEFAULT_VISIBILITY,
1686             ident: ti.ident,
1687             ty,
1688             mutability: ast::Mutability::Immutable,
1689             expr_opt: expr_opt.as_ref(),
1690             defaultness: None,
1691             span: ti.span,
1692         }
1693     }
1694
1695     pub(crate) fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1696         let (ty, expr) = match ii.kind {
1697             ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1698             _ => unreachable!(),
1699         };
1700         StaticParts {
1701             prefix: "const",
1702             vis: &ii.vis,
1703             ident: ii.ident,
1704             ty,
1705             mutability: ast::Mutability::Immutable,
1706             expr_opt: Some(expr),
1707             defaultness: Some(ii.defaultness),
1708             span: ii.span,
1709         }
1710     }
1711 }
1712
1713 fn rewrite_static(
1714     context: &RewriteContext<'_>,
1715     static_parts: &StaticParts<'_>,
1716     offset: Indent,
1717 ) -> Option<String> {
1718     let colon = colon_spaces(context.config);
1719     let mut prefix = format!(
1720         "{}{}{} {}{}{}",
1721         format_visibility(context, static_parts.vis),
1722         static_parts.defaultness.map_or("", format_defaultness),
1723         static_parts.prefix,
1724         format_mutability(static_parts.mutability),
1725         rewrite_ident(context, static_parts.ident),
1726         colon,
1727     );
1728     // 2 = " =".len()
1729     let ty_shape =
1730         Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1731     let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1732         Some(ty_str) => ty_str,
1733         None => {
1734             if prefix.ends_with(' ') {
1735                 prefix.pop();
1736             }
1737             let nested_indent = offset.block_indent(context.config);
1738             let nested_shape = Shape::indented(nested_indent, context.config);
1739             let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1740             format!(
1741                 "{}{}",
1742                 nested_indent.to_string_with_newline(context.config),
1743                 ty_str
1744             )
1745         }
1746     };
1747
1748     if let Some(expr) = static_parts.expr_opt {
1749         let lhs = format!("{}{} =", prefix, ty_str);
1750         // 1 = ;
1751         let remaining_width = context.budget(offset.block_indent + 1);
1752         rewrite_assign_rhs(
1753             context,
1754             lhs,
1755             &**expr,
1756             Shape::legacy(remaining_width, offset.block_only()),
1757         )
1758         .and_then(|res| recover_comment_removed(res, static_parts.span, context))
1759         .map(|s| if s.ends_with(';') { s } else { s + ";" })
1760     } else {
1761         Some(format!("{}{};", prefix, ty_str))
1762     }
1763 }
1764
1765 pub(crate) fn rewrite_associated_type(
1766     ident: ast::Ident,
1767     ty_opt: Option<&ptr::P<ast::Ty>>,
1768     generics: &ast::Generics,
1769     generic_bounds_opt: Option<&ast::GenericBounds>,
1770     context: &RewriteContext<'_>,
1771     indent: Indent,
1772 ) -> Option<String> {
1773     let ident_str = rewrite_ident(context, ident);
1774     // 5 = "type "
1775     let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
1776     let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
1777     let prefix = format!("type {}", generics_str);
1778
1779     let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
1780         if bounds.is_empty() {
1781             String::new()
1782         } else {
1783             // 2 = ": ".len()
1784             let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1785             bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1786         }
1787     } else {
1788         String::new()
1789     };
1790
1791     if let Some(ty) = ty_opt {
1792         // 1 = `;`
1793         let shape = Shape::indented(indent, context.config).sub_width(1)?;
1794         let lhs = format!("{}{} =", prefix, type_bounds_str);
1795         rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1796     } else {
1797         Some(format!("{}{};", prefix, type_bounds_str))
1798     }
1799 }
1800
1801 struct OpaqueType<'a> {
1802     bounds: &'a ast::GenericBounds,
1803 }
1804
1805 impl<'a> Rewrite for OpaqueType<'a> {
1806     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1807         let shape = shape.offset_left(5)?; // `impl `
1808         self.bounds
1809             .rewrite(context, shape)
1810             .map(|s| format!("impl {}", s))
1811     }
1812 }
1813
1814 pub(crate) fn rewrite_opaque_impl_type(
1815     context: &RewriteContext<'_>,
1816     ident: ast::Ident,
1817     generics: &ast::Generics,
1818     generic_bounds: &ast::GenericBounds,
1819     indent: Indent,
1820 ) -> Option<String> {
1821     let ident_str = rewrite_ident(context, ident);
1822     // 5 = "type "
1823     let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
1824     let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
1825     let prefix = format!("type {} =", generics_str);
1826     let rhs = OpaqueType {
1827         bounds: generic_bounds,
1828     };
1829
1830     rewrite_assign_rhs(
1831         context,
1832         &prefix,
1833         &rhs,
1834         Shape::indented(indent, context.config).sub_width(1)?,
1835     )
1836     .map(|s| s + ";")
1837 }
1838
1839 pub(crate) fn rewrite_associated_impl_type(
1840     ident: ast::Ident,
1841     defaultness: ast::Defaultness,
1842     ty_opt: Option<&ptr::P<ast::Ty>>,
1843     generics: &ast::Generics,
1844     context: &RewriteContext<'_>,
1845     indent: Indent,
1846 ) -> Option<String> {
1847     let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
1848
1849     match defaultness {
1850         ast::Defaultness::Default => Some(format!("default {}", result)),
1851         _ => Some(result),
1852     }
1853 }
1854
1855 impl Rewrite for ast::FunctionRetTy {
1856     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1857         match *self {
1858             ast::FunctionRetTy::Default(_) => Some(String::new()),
1859             ast::FunctionRetTy::Ty(ref ty) => {
1860                 if context.config.version() == Version::One
1861                     || context.config.indent_style() == IndentStyle::Visual
1862                 {
1863                     let inner_width = shape.width.checked_sub(3)?;
1864                     return ty
1865                         .rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1866                         .map(|r| format!("-> {}", r));
1867                 }
1868
1869                 ty.rewrite(context, shape.offset_left(3)?)
1870                     .map(|s| format!("-> {}", s))
1871             }
1872         }
1873     }
1874 }
1875
1876 fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
1877     match ty.kind {
1878         ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
1879         _ => false,
1880     }
1881 }
1882
1883 /// Recover any missing comments between the param and the type.
1884 ///
1885 /// # Returns
1886 ///
1887 /// A 2-len tuple with the comment before the colon in first position, and the comment after the
1888 /// colon in second position.
1889 fn get_missing_param_comments(
1890     context: &RewriteContext<'_>,
1891     pat_span: Span,
1892     ty_span: Span,
1893     shape: Shape,
1894 ) -> (String, String) {
1895     let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
1896
1897     let span_before_colon = {
1898         let missing_comment_span_hi = context
1899             .snippet_provider
1900             .span_before(missing_comment_span, ":");
1901         mk_sp(pat_span.hi(), missing_comment_span_hi)
1902     };
1903     let span_after_colon = {
1904         let missing_comment_span_lo = context
1905             .snippet_provider
1906             .span_after(missing_comment_span, ":");
1907         mk_sp(missing_comment_span_lo, ty_span.lo())
1908     };
1909
1910     let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
1911         .filter(|comment| !comment.is_empty())
1912         .map_or(String::new(), |comment| format!(" {}", comment));
1913     let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
1914         .filter(|comment| !comment.is_empty())
1915         .map_or(String::new(), |comment| format!("{} ", comment));
1916     (comment_before_colon, comment_after_colon)
1917 }
1918
1919 impl Rewrite for ast::Param {
1920     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1921         let param_attrs_result = self
1922             .attrs
1923             .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1924         let (span, has_multiple_attr_lines) = if !self.attrs.is_empty() {
1925             let num_attrs = self.attrs.len();
1926             (
1927                 mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
1928                 param_attrs_result.contains("\n"),
1929             )
1930         } else {
1931             (mk_sp(self.span.lo(), self.span.lo()), false)
1932         };
1933
1934         if let Some(ref explicit_self) = self.to_self() {
1935             rewrite_explicit_self(
1936                 context,
1937                 explicit_self,
1938                 &param_attrs_result,
1939                 span,
1940                 shape,
1941                 has_multiple_attr_lines,
1942             )
1943         } else if is_named_param(self) {
1944             let mut result = combine_strs_with_missing_comments(
1945                 context,
1946                 &param_attrs_result,
1947                 &self
1948                     .pat
1949                     .rewrite(context, Shape::legacy(shape.width, shape.indent))?,
1950                 span,
1951                 shape,
1952                 !has_multiple_attr_lines,
1953             )?;
1954
1955             if !is_empty_infer(&*self.ty, self.pat.span) {
1956                 let (before_comment, after_comment) =
1957                     get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
1958                 result.push_str(&before_comment);
1959                 result.push_str(colon_spaces(context.config));
1960                 result.push_str(&after_comment);
1961                 let overhead = last_line_width(&result);
1962                 let max_width = shape.width.checked_sub(overhead)?;
1963                 let ty_str = self
1964                     .ty
1965                     .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1966                 result.push_str(&ty_str);
1967             }
1968
1969             Some(result)
1970         } else {
1971             self.ty.rewrite(context, shape)
1972         }
1973     }
1974 }
1975
1976 fn rewrite_explicit_self(
1977     context: &RewriteContext<'_>,
1978     explicit_self: &ast::ExplicitSelf,
1979     param_attrs: &str,
1980     span: Span,
1981     shape: Shape,
1982     has_multiple_attr_lines: bool,
1983 ) -> Option<String> {
1984     match explicit_self.node {
1985         ast::SelfKind::Region(lt, m) => {
1986             let mut_str = format_mutability(m);
1987             match lt {
1988                 Some(ref l) => {
1989                     let lifetime_str = l.rewrite(
1990                         context,
1991                         Shape::legacy(context.config.max_width(), Indent::empty()),
1992                     )?;
1993                     Some(combine_strs_with_missing_comments(
1994                         context,
1995                         &param_attrs,
1996                         &format!("&{} {}self", lifetime_str, mut_str),
1997                         span,
1998                         shape,
1999                         !has_multiple_attr_lines,
2000                     )?)
2001                 }
2002                 None => Some(combine_strs_with_missing_comments(
2003                     context,
2004                     &param_attrs,
2005                     &format!("&{}self", mut_str),
2006                     span,
2007                     shape,
2008                     !has_multiple_attr_lines,
2009                 )?),
2010             }
2011         }
2012         ast::SelfKind::Explicit(ref ty, mutability) => {
2013             let type_str = ty.rewrite(
2014                 context,
2015                 Shape::legacy(context.config.max_width(), Indent::empty()),
2016             )?;
2017
2018             Some(combine_strs_with_missing_comments(
2019                 context,
2020                 &param_attrs,
2021                 &format!("{}self: {}", format_mutability(mutability), type_str),
2022                 span,
2023                 shape,
2024                 !has_multiple_attr_lines,
2025             )?)
2026         }
2027         ast::SelfKind::Value(mutability) => Some(combine_strs_with_missing_comments(
2028             context,
2029             &param_attrs,
2030             &format!("{}self", format_mutability(mutability)),
2031             span,
2032             shape,
2033             !has_multiple_attr_lines,
2034         )?),
2035     }
2036 }
2037
2038 pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2039     if param.attrs.is_empty() {
2040         if is_named_param(param) {
2041             param.pat.span.lo()
2042         } else {
2043             param.ty.span.lo()
2044         }
2045     } else {
2046         param.attrs[0].span.lo()
2047     }
2048 }
2049
2050 pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2051     match param.ty.kind {
2052         ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2053         ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2054         _ => param.ty.span.hi(),
2055     }
2056 }
2057
2058 pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2059     if let ast::PatKind::Ident(_, ident, _) = param.pat.kind {
2060         ident.name != symbol::kw::Invalid
2061     } else {
2062         true
2063     }
2064 }
2065
2066 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2067 pub(crate) enum FnBraceStyle {
2068     SameLine,
2069     NextLine,
2070     None,
2071 }
2072
2073 // Return type is (result, force_new_line_for_brace)
2074 fn rewrite_fn_base(
2075     context: &RewriteContext<'_>,
2076     indent: Indent,
2077     ident: ast::Ident,
2078     fn_sig: &FnSig<'_>,
2079     span: Span,
2080     fn_brace_style: FnBraceStyle,
2081 ) -> Option<(String, bool)> {
2082     let mut force_new_line_for_brace = false;
2083
2084     let where_clause = &fn_sig.generics.where_clause;
2085
2086     let mut result = String::with_capacity(1024);
2087     result.push_str(&fn_sig.to_str(context));
2088
2089     // fn foo
2090     result.push_str("fn ");
2091
2092     // Generics.
2093     let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2094         // 4 = `() {`
2095         4
2096     } else {
2097         // 2 = `()`
2098         2
2099     };
2100     let used_width = last_line_used_width(&result, indent.width());
2101     let one_line_budget = context.budget(used_width + overhead);
2102     let shape = Shape {
2103         width: one_line_budget,
2104         indent,
2105         offset: used_width,
2106     };
2107     let fd = fn_sig.decl;
2108     let generics_str = rewrite_generics(
2109         context,
2110         rewrite_ident(context, ident),
2111         fn_sig.generics,
2112         shape,
2113     )?;
2114     result.push_str(&generics_str);
2115
2116     let snuggle_angle_bracket = generics_str
2117         .lines()
2118         .last()
2119         .map_or(false, |l| l.trim_start().len() == 1);
2120
2121     // Note that the width and indent don't really matter, we'll re-layout the
2122     // return type later anyway.
2123     let ret_str = fd
2124         .output
2125         .rewrite(context, Shape::indented(indent, context.config))?;
2126
2127     let multi_line_ret_str = ret_str.contains('\n');
2128     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2129
2130     // Params.
2131     let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2132         context,
2133         &result,
2134         indent,
2135         ret_str_len,
2136         fn_brace_style,
2137         multi_line_ret_str,
2138     )?;
2139
2140     debug!(
2141         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2142         one_line_budget, multi_line_budget, param_indent
2143     );
2144
2145     result.push('(');
2146     // Check if vertical layout was forced.
2147     if one_line_budget == 0
2148         && !snuggle_angle_bracket
2149         && context.config.indent_style() == IndentStyle::Visual
2150     {
2151         result.push_str(&param_indent.to_string_with_newline(context.config));
2152     }
2153
2154     // Skip `pub(crate)`.
2155     let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
2156     // A conservative estimation, to goal is to be over all parens in generics
2157     let params_start = fn_sig
2158         .generics
2159         .params
2160         .iter()
2161         .last()
2162         .map_or(lo_after_visibility, |param| param.span().hi());
2163     let params_end = if fd.inputs.is_empty() {
2164         context
2165             .snippet_provider
2166             .span_after(mk_sp(params_start, span.hi()), ")")
2167     } else {
2168         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2169         context.snippet_provider.span_after(last_span, ")")
2170     };
2171     let params_span = mk_sp(
2172         context
2173             .snippet_provider
2174             .span_after(mk_sp(params_start, span.hi()), "("),
2175         params_end,
2176     );
2177     let param_str = rewrite_params(
2178         context,
2179         &fd.inputs,
2180         one_line_budget,
2181         multi_line_budget,
2182         indent,
2183         param_indent,
2184         params_span,
2185         fd.c_variadic(),
2186     )?;
2187
2188     let put_params_in_block = match context.config.indent_style() {
2189         IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2190         _ => false,
2191     } && !fd.inputs.is_empty();
2192
2193     let mut params_last_line_contains_comment = false;
2194     let mut no_params_and_over_max_width = false;
2195
2196     if put_params_in_block {
2197         param_indent = indent.block_indent(context.config);
2198         result.push_str(&param_indent.to_string_with_newline(context.config));
2199         result.push_str(&param_str);
2200         result.push_str(&indent.to_string_with_newline(context.config));
2201         result.push(')');
2202     } else {
2203         result.push_str(&param_str);
2204         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2205         // Put the closing brace on the next line if it overflows the max width.
2206         // 1 = `)`
2207         let closing_paren_overflow_max_width =
2208             fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2209         // If the last line of params contains comment, we cannot put the closing paren
2210         // on the same line.
2211         params_last_line_contains_comment = param_str
2212             .lines()
2213             .last()
2214             .map_or(false, |last_line| last_line.contains("//"));
2215
2216         if context.config.version() == Version::Two {
2217             result.push(')');
2218             if closing_paren_overflow_max_width || params_last_line_contains_comment {
2219                 result.push_str(&indent.to_string_with_newline(context.config));
2220                 no_params_and_over_max_width = true;
2221             }
2222         } else {
2223             if closing_paren_overflow_max_width || params_last_line_contains_comment {
2224                 result.push_str(&indent.to_string_with_newline(context.config));
2225             }
2226             result.push(')');
2227         }
2228     }
2229
2230     // Return type.
2231     if let ast::FunctionRetTy::Ty(..) = fd.output {
2232         let ret_should_indent = match context.config.indent_style() {
2233             // If our params are block layout then we surely must have space.
2234             IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2235             _ if params_last_line_contains_comment => false,
2236             _ if result.contains('\n') || multi_line_ret_str => true,
2237             _ => {
2238                 // If the return type would push over the max width, then put the return type on
2239                 // a new line. With the +1 for the signature length an additional space between
2240                 // the closing parenthesis of the param and the arrow '->' is considered.
2241                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2242
2243                 // If there is no where-clause, take into account the space after the return type
2244                 // and the brace.
2245                 if where_clause.predicates.is_empty() {
2246                     sig_length += 2;
2247                 }
2248
2249                 sig_length > context.config.max_width()
2250             }
2251         };
2252         let ret_shape = if ret_should_indent {
2253             if context.config.version() == Version::One
2254                 || context.config.indent_style() == IndentStyle::Visual
2255             {
2256                 let indent = if param_str.is_empty() {
2257                     // Aligning with non-existent params looks silly.
2258                     force_new_line_for_brace = true;
2259                     indent + 4
2260                 } else {
2261                     // FIXME: we might want to check that using the param indent
2262                     // doesn't blow our budget, and if it does, then fallback to
2263                     // the where-clause indent.
2264                     param_indent
2265                 };
2266
2267                 result.push_str(&indent.to_string_with_newline(context.config));
2268                 Shape::indented(indent, context.config)
2269             } else {
2270                 let mut ret_shape = Shape::indented(indent, context.config);
2271                 if param_str.is_empty() {
2272                     // Aligning with non-existent params looks silly.
2273                     force_new_line_for_brace = true;
2274                     ret_shape = if context.use_block_indent() {
2275                         ret_shape.offset_left(4).unwrap_or(ret_shape)
2276                     } else {
2277                         ret_shape.indent = ret_shape.indent + 4;
2278                         ret_shape
2279                     };
2280                 }
2281
2282                 result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2283                 ret_shape
2284             }
2285         } else {
2286             if context.config.version() == Version::Two {
2287                 if !param_str.is_empty() || !no_params_and_over_max_width {
2288                     result.push(' ');
2289                 }
2290             } else {
2291                 result.push(' ');
2292             }
2293
2294             let ret_shape = Shape::indented(indent, context.config);
2295             ret_shape
2296                 .offset_left(last_line_width(&result))
2297                 .unwrap_or(ret_shape)
2298         };
2299
2300         if multi_line_ret_str || ret_should_indent {
2301             // Now that we know the proper indent and width, we need to
2302             // re-layout the return type.
2303             let ret_str = fd.output.rewrite(context, ret_shape)?;
2304             result.push_str(&ret_str);
2305         } else {
2306             result.push_str(&ret_str);
2307         }
2308
2309         // Comment between return type and the end of the decl.
2310         let snippet_lo = fd.output.span().hi();
2311         if where_clause.predicates.is_empty() {
2312             let snippet_hi = span.hi();
2313             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2314             // Try to preserve the layout of the original snippet.
2315             let original_starts_with_newline = snippet
2316                 .find(|c| c != ' ')
2317                 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2318             let original_ends_with_newline = snippet
2319                 .rfind(|c| c != ' ')
2320                 .map_or(false, |i| snippet[i..].ends_with('\n'));
2321             let snippet = snippet.trim();
2322             if !snippet.is_empty() {
2323                 result.push(if original_starts_with_newline {
2324                     '\n'
2325                 } else {
2326                     ' '
2327                 });
2328                 result.push_str(snippet);
2329                 if original_ends_with_newline {
2330                     force_new_line_for_brace = true;
2331                 }
2332             }
2333         }
2334     }
2335
2336     let pos_before_where = match fd.output {
2337         ast::FunctionRetTy::Default(..) => params_span.hi(),
2338         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2339     };
2340
2341     let is_params_multi_lined = param_str.contains('\n');
2342
2343     let space = if put_params_in_block && ret_str.is_empty() {
2344         WhereClauseSpace::Space
2345     } else {
2346         WhereClauseSpace::Newline
2347     };
2348     let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2349     if is_params_multi_lined {
2350         option.veto_single_line();
2351     }
2352     let where_clause_str = rewrite_where_clause(
2353         context,
2354         where_clause,
2355         context.config.brace_style(),
2356         Shape::indented(indent, context.config),
2357         true,
2358         "{",
2359         Some(span.hi()),
2360         pos_before_where,
2361         option,
2362     )?;
2363     // If there are neither where-clause nor return type, we may be missing comments between
2364     // params and `{`.
2365     if where_clause_str.is_empty() {
2366         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2367             match recover_missing_comment_in_span(
2368                 mk_sp(params_span.hi(), ret_span.hi()),
2369                 shape,
2370                 context,
2371                 last_line_width(&result),
2372             ) {
2373                 Some(ref missing_comment) if !missing_comment.is_empty() => {
2374                     result.push_str(missing_comment);
2375                     force_new_line_for_brace = true;
2376                 }
2377                 _ => (),
2378             }
2379         }
2380     }
2381
2382     result.push_str(&where_clause_str);
2383
2384     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2385     force_new_line_for_brace |= is_params_multi_lined && context.config.where_single_line();
2386     Some((result, force_new_line_for_brace))
2387 }
2388
2389 /// Kind of spaces to put before `where`.
2390 #[derive(Copy, Clone)]
2391 enum WhereClauseSpace {
2392     /// A single space.
2393     Space,
2394     /// A new line.
2395     Newline,
2396     /// Nothing.
2397     None,
2398 }
2399
2400 #[derive(Copy, Clone)]
2401 struct WhereClauseOption {
2402     suppress_comma: bool, // Force no trailing comma
2403     snuggle: WhereClauseSpace,
2404     allow_single_line: bool, // Try single line where-clause instead of vertical layout
2405     veto_single_line: bool,  // Disallow a single-line where-clause.
2406 }
2407
2408 impl WhereClauseOption {
2409     fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2410         WhereClauseOption {
2411             suppress_comma,
2412             snuggle,
2413             allow_single_line: false,
2414             veto_single_line: false,
2415         }
2416     }
2417
2418     fn snuggled(current: &str) -> WhereClauseOption {
2419         WhereClauseOption {
2420             suppress_comma: false,
2421             snuggle: if last_line_width(current) == 1 {
2422                 WhereClauseSpace::Space
2423             } else {
2424                 WhereClauseSpace::Newline
2425             },
2426             allow_single_line: false,
2427             veto_single_line: false,
2428         }
2429     }
2430
2431     fn suppress_comma(&mut self) {
2432         self.suppress_comma = true
2433     }
2434
2435     fn allow_single_line(&mut self) {
2436         self.allow_single_line = true
2437     }
2438
2439     fn snuggle(&mut self) {
2440         self.snuggle = WhereClauseSpace::Space
2441     }
2442
2443     fn veto_single_line(&mut self) {
2444         self.veto_single_line = true;
2445     }
2446 }
2447
2448 fn rewrite_params(
2449     context: &RewriteContext<'_>,
2450     params: &[ast::Param],
2451     one_line_budget: usize,
2452     multi_line_budget: usize,
2453     indent: Indent,
2454     param_indent: Indent,
2455     span: Span,
2456     variadic: bool,
2457 ) -> Option<String> {
2458     if params.is_empty() {
2459         let comment = context
2460             .snippet(mk_sp(
2461                 span.lo(),
2462                 // to remove ')'
2463                 span.hi() - BytePos(1),
2464             ))
2465             .trim();
2466         return Some(comment.to_owned());
2467     }
2468     let param_items: Vec<_> = itemize_list(
2469         context.snippet_provider,
2470         params.iter(),
2471         ")",
2472         ",",
2473         |param| span_lo_for_param(param),
2474         |param| param.ty.span.hi(),
2475         |param| {
2476             param
2477                 .rewrite(context, Shape::legacy(multi_line_budget, param_indent))
2478                 .or_else(|| Some(context.snippet(param.span()).to_owned()))
2479         },
2480         span.lo(),
2481         span.hi(),
2482         false,
2483     )
2484     .collect();
2485
2486     let tactic = definitive_tactic(
2487         &param_items,
2488         context
2489             .config
2490             .fn_args_layout()
2491             .to_list_tactic(param_items.len()),
2492         Separator::Comma,
2493         one_line_budget,
2494     );
2495     let budget = match tactic {
2496         DefinitiveListTactic::Horizontal => one_line_budget,
2497         _ => multi_line_budget,
2498     };
2499     let indent = match context.config.indent_style() {
2500         IndentStyle::Block => indent.block_indent(context.config),
2501         IndentStyle::Visual => param_indent,
2502     };
2503     let trailing_separator = if variadic {
2504         SeparatorTactic::Never
2505     } else {
2506         match context.config.indent_style() {
2507             IndentStyle::Block => context.config.trailing_comma(),
2508             IndentStyle::Visual => SeparatorTactic::Never,
2509         }
2510     };
2511     let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2512         .tactic(tactic)
2513         .trailing_separator(trailing_separator)
2514         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2515         .preserve_newline(true);
2516     write_list(&param_items, &fmt)
2517 }
2518
2519 fn compute_budgets_for_params(
2520     context: &RewriteContext<'_>,
2521     result: &str,
2522     indent: Indent,
2523     ret_str_len: usize,
2524     fn_brace_style: FnBraceStyle,
2525     force_vertical_layout: bool,
2526 ) -> Option<((usize, usize, Indent))> {
2527     debug!(
2528         "compute_budgets_for_params {} {:?}, {}, {:?}",
2529         result.len(),
2530         indent,
2531         ret_str_len,
2532         fn_brace_style,
2533     );
2534     // Try keeping everything on the same line.
2535     if !result.contains('\n') && !force_vertical_layout {
2536         // 2 = `()`, 3 = `() `, space is before ret_string.
2537         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2538         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2539         match fn_brace_style {
2540             FnBraceStyle::None => used_space += 1,     // 1 = `;`
2541             FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2542             FnBraceStyle::NextLine => (),
2543         }
2544         let one_line_budget = context.budget(used_space);
2545
2546         if one_line_budget > 0 {
2547             // 4 = "() {".len()
2548             let (indent, multi_line_budget) = match context.config.indent_style() {
2549                 IndentStyle::Block => {
2550                     let indent = indent.block_indent(context.config);
2551                     (indent, context.budget(indent.width() + 1))
2552                 }
2553                 IndentStyle::Visual => {
2554                     let indent = indent + result.len() + 1;
2555                     let multi_line_overhead = match fn_brace_style {
2556                         FnBraceStyle::SameLine => 4,
2557                         _ => 2,
2558                     } + indent.width();
2559                     (indent, context.budget(multi_line_overhead))
2560                 }
2561             };
2562
2563             return Some((one_line_budget, multi_line_budget, indent));
2564         }
2565     }
2566
2567     // Didn't work. we must force vertical layout and put params on a newline.
2568     let new_indent = indent.block_indent(context.config);
2569     let used_space = match context.config.indent_style() {
2570         // 1 = `,`
2571         IndentStyle::Block => new_indent.width() + 1,
2572         // Account for `)` and possibly ` {`.
2573         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2574     };
2575     Some((0, context.budget(used_space), new_indent))
2576 }
2577
2578 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2579     let predicate_count = where_clause.predicates.len();
2580
2581     if config.where_single_line() && predicate_count == 1 {
2582         return FnBraceStyle::SameLine;
2583     }
2584     let brace_style = config.brace_style();
2585
2586     let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2587         || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2588     if use_next_line {
2589         FnBraceStyle::NextLine
2590     } else {
2591         FnBraceStyle::SameLine
2592     }
2593 }
2594
2595 fn rewrite_generics(
2596     context: &RewriteContext<'_>,
2597     ident: &str,
2598     generics: &ast::Generics,
2599     shape: Shape,
2600 ) -> Option<String> {
2601     // FIXME: convert bounds to where-clauses where they get too big or if
2602     // there is a where-clause at all.
2603
2604     if generics.params.is_empty() {
2605         return Some(ident.to_owned());
2606     }
2607
2608     let params = generics.params.iter();
2609     overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2610 }
2611
2612 pub(crate) fn generics_shape_from_config(
2613     config: &Config,
2614     shape: Shape,
2615     offset: usize,
2616 ) -> Option<Shape> {
2617     match config.indent_style() {
2618         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2619         IndentStyle::Block => {
2620             // 1 = ","
2621             shape
2622                 .block()
2623                 .block_indent(config.tab_spaces())
2624                 .with_max_width(config)
2625                 .sub_width(1)
2626         }
2627     }
2628 }
2629
2630 fn rewrite_where_clause_rfc_style(
2631     context: &RewriteContext<'_>,
2632     where_clause: &ast::WhereClause,
2633     shape: Shape,
2634     terminator: &str,
2635     span_end: Option<BytePos>,
2636     span_end_before_where: BytePos,
2637     where_clause_option: WhereClauseOption,
2638 ) -> Option<String> {
2639     let (where_keyword, allow_single_line) = rewrite_where_keyword(
2640         context,
2641         where_clause,
2642         shape,
2643         span_end_before_where,
2644         where_clause_option,
2645     )?;
2646
2647     // 1 = `,`
2648     let clause_shape = shape
2649         .block()
2650         .with_max_width(context.config)
2651         .block_left(context.config.tab_spaces())?
2652         .sub_width(1)?;
2653     let force_single_line = context.config.where_single_line()
2654         && where_clause.predicates.len() == 1
2655         && !where_clause_option.veto_single_line;
2656
2657     let preds_str = rewrite_bounds_on_where_clause(
2658         context,
2659         where_clause,
2660         clause_shape,
2661         terminator,
2662         span_end,
2663         where_clause_option,
2664         force_single_line,
2665     )?;
2666
2667     // 6 = `where `
2668     let clause_sep =
2669         if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
2670             || force_single_line
2671         {
2672             Cow::from(" ")
2673         } else {
2674             clause_shape.indent.to_string_with_newline(context.config)
2675         };
2676
2677     Some(format!("{}{}{}", where_keyword, clause_sep, preds_str))
2678 }
2679
2680 /// Rewrite `where` and comment around it.
2681 fn rewrite_where_keyword(
2682     context: &RewriteContext<'_>,
2683     where_clause: &ast::WhereClause,
2684     shape: Shape,
2685     span_end_before_where: BytePos,
2686     where_clause_option: WhereClauseOption,
2687 ) -> Option<(String, bool)> {
2688     let block_shape = shape.block().with_max_width(context.config);
2689     // 1 = `,`
2690     let clause_shape = block_shape
2691         .block_left(context.config.tab_spaces())?
2692         .sub_width(1)?;
2693
2694     let comment_separator = |comment: &str, shape: Shape| {
2695         if comment.is_empty() {
2696             Cow::from("")
2697         } else {
2698             shape.indent.to_string_with_newline(context.config)
2699         }
2700     };
2701
2702     let (span_before, span_after) =
2703         missing_span_before_after_where(span_end_before_where, where_clause);
2704     let (comment_before, comment_after) =
2705         rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2706
2707     let starting_newline = match where_clause_option.snuggle {
2708         WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
2709         WhereClauseSpace::None => Cow::from(""),
2710         _ => block_shape.indent.to_string_with_newline(context.config),
2711     };
2712
2713     let newline_before_where = comment_separator(&comment_before, shape);
2714     let newline_after_where = comment_separator(&comment_after, clause_shape);
2715     let result = format!(
2716         "{}{}{}where{}{}",
2717         starting_newline, comment_before, newline_before_where, newline_after_where, comment_after
2718     );
2719     let allow_single_line = where_clause_option.allow_single_line
2720         && comment_before.is_empty()
2721         && comment_after.is_empty();
2722
2723     Some((result, allow_single_line))
2724 }
2725
2726 /// Rewrite bounds on a where clause.
2727 fn rewrite_bounds_on_where_clause(
2728     context: &RewriteContext<'_>,
2729     where_clause: &ast::WhereClause,
2730     shape: Shape,
2731     terminator: &str,
2732     span_end: Option<BytePos>,
2733     where_clause_option: WhereClauseOption,
2734     force_single_line: bool,
2735 ) -> Option<String> {
2736     let span_start = where_clause.predicates[0].span().lo();
2737     // If we don't have the start of the next span, then use the end of the
2738     // predicates, but that means we miss comments.
2739     let len = where_clause.predicates.len();
2740     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2741     let span_end = span_end.unwrap_or(end_of_preds);
2742     let items = itemize_list(
2743         context.snippet_provider,
2744         where_clause.predicates.iter(),
2745         terminator,
2746         ",",
2747         |pred| pred.span().lo(),
2748         |pred| pred.span().hi(),
2749         |pred| pred.rewrite(context, shape),
2750         span_start,
2751         span_end,
2752         false,
2753     );
2754     let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
2755         SeparatorTactic::Never
2756     } else {
2757         context.config.trailing_comma()
2758     };
2759
2760     // shape should be vertical only and only if we have `force_single_line` option enabled
2761     // and the number of items of the where-clause is equal to 1
2762     let shape_tactic = if force_single_line {
2763         DefinitiveListTactic::Horizontal
2764     } else {
2765         DefinitiveListTactic::Vertical
2766     };
2767
2768     let fmt = ListFormatting::new(shape, context.config)
2769         .tactic(shape_tactic)
2770         .trailing_separator(comma_tactic)
2771         .preserve_newline(true);
2772     write_list(&items.collect::<Vec<_>>(), &fmt)
2773 }
2774
2775 fn rewrite_where_clause(
2776     context: &RewriteContext<'_>,
2777     where_clause: &ast::WhereClause,
2778     brace_style: BraceStyle,
2779     shape: Shape,
2780     on_new_line: bool,
2781     terminator: &str,
2782     span_end: Option<BytePos>,
2783     span_end_before_where: BytePos,
2784     where_clause_option: WhereClauseOption,
2785 ) -> Option<String> {
2786     if where_clause.predicates.is_empty() {
2787         return Some(String::new());
2788     }
2789
2790     if context.config.indent_style() == IndentStyle::Block {
2791         return rewrite_where_clause_rfc_style(
2792             context,
2793             where_clause,
2794             shape,
2795             terminator,
2796             span_end,
2797             span_end_before_where,
2798             where_clause_option,
2799         );
2800     }
2801
2802     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2803
2804     let offset = match context.config.indent_style() {
2805         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2806         // 6 = "where ".len()
2807         IndentStyle::Visual => shape.indent + extra_indent + 6,
2808     };
2809     // FIXME: if indent_style != Visual, then the budgets below might
2810     // be out by a char or two.
2811
2812     let budget = context.config.max_width() - offset.width();
2813     let span_start = where_clause.predicates[0].span().lo();
2814     // If we don't have the start of the next span, then use the end of the
2815     // predicates, but that means we miss comments.
2816     let len = where_clause.predicates.len();
2817     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2818     let span_end = span_end.unwrap_or(end_of_preds);
2819     let items = itemize_list(
2820         context.snippet_provider,
2821         where_clause.predicates.iter(),
2822         terminator,
2823         ",",
2824         |pred| pred.span().lo(),
2825         |pred| pred.span().hi(),
2826         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2827         span_start,
2828         span_end,
2829         false,
2830     );
2831     let item_vec = items.collect::<Vec<_>>();
2832     // FIXME: we don't need to collect here
2833     let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2834
2835     let mut comma_tactic = context.config.trailing_comma();
2836     // Kind of a hack because we don't usually have trailing commas in where-clauses.
2837     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2838         comma_tactic = SeparatorTactic::Never;
2839     }
2840
2841     let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
2842         .tactic(tactic)
2843         .trailing_separator(comma_tactic)
2844         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2845         .preserve_newline(true);
2846     let preds_str = write_list(&item_vec, &fmt)?;
2847
2848     let end_length = if terminator == "{" {
2849         // If the brace is on the next line we don't need to count it otherwise it needs two
2850         // characters " {"
2851         match brace_style {
2852             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2853             BraceStyle::PreferSameLine => 2,
2854         }
2855     } else if terminator == "=" {
2856         2
2857     } else {
2858         terminator.len()
2859     };
2860     if on_new_line
2861         || preds_str.contains('\n')
2862         || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2863     {
2864         Some(format!(
2865             "\n{}where {}",
2866             (shape.indent + extra_indent).to_string(context.config),
2867             preds_str
2868         ))
2869     } else {
2870         Some(format!(" where {}", preds_str))
2871     }
2872 }
2873
2874 fn missing_span_before_after_where(
2875     before_item_span_end: BytePos,
2876     where_clause: &ast::WhereClause,
2877 ) -> (Span, Span) {
2878     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2879     // 5 = `where`
2880     let pos_after_where = where_clause.span.lo() + BytePos(5);
2881     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2882     (missing_span_before, missing_span_after)
2883 }
2884
2885 fn rewrite_comments_before_after_where(
2886     context: &RewriteContext<'_>,
2887     span_before_where: Span,
2888     span_after_where: Span,
2889     shape: Shape,
2890 ) -> Option<(String, String)> {
2891     let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2892     let after_comment = rewrite_missing_comment(
2893         span_after_where,
2894         shape.block_indent(context.config.tab_spaces()),
2895         context,
2896     )?;
2897     Some((before_comment, after_comment))
2898 }
2899
2900 fn format_header(
2901     context: &RewriteContext<'_>,
2902     item_name: &str,
2903     ident: ast::Ident,
2904     vis: &ast::Visibility,
2905 ) -> String {
2906     format!(
2907         "{}{}{}",
2908         format_visibility(context, vis),
2909         item_name,
2910         rewrite_ident(context, ident)
2911     )
2912 }
2913
2914 #[derive(PartialEq, Eq, Clone, Copy)]
2915 enum BracePos {
2916     None,
2917     Auto,
2918     ForceSameLine,
2919 }
2920
2921 fn format_generics(
2922     context: &RewriteContext<'_>,
2923     generics: &ast::Generics,
2924     brace_style: BraceStyle,
2925     brace_pos: BracePos,
2926     offset: Indent,
2927     span: Span,
2928     used_width: usize,
2929 ) -> Option<String> {
2930     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2931     let mut result = rewrite_generics(context, "", generics, shape)?;
2932
2933     // If the generics are not parameterized then generics.span.hi() == 0,
2934     // so we use span.lo(), which is the position after `struct Foo`.
2935     let span_end_before_where = if !generics.params.is_empty() {
2936         generics.span.hi()
2937     } else {
2938         span.lo()
2939     };
2940     let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
2941         let budget = context.budget(last_line_used_width(&result, offset.width()));
2942         let mut option = WhereClauseOption::snuggled(&result);
2943         if brace_pos == BracePos::None {
2944             option.suppress_comma = true;
2945         }
2946         let where_clause_str = rewrite_where_clause(
2947             context,
2948             &generics.where_clause,
2949             brace_style,
2950             Shape::legacy(budget, offset.block_only()),
2951             true,
2952             "{",
2953             Some(span.hi()),
2954             span_end_before_where,
2955             option,
2956         )?;
2957         result.push_str(&where_clause_str);
2958         (
2959             brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
2960             // missed comments are taken care of in #rewrite_where_clause
2961             None,
2962         )
2963     } else {
2964         (
2965             brace_pos == BracePos::ForceSameLine
2966                 || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
2967                     || brace_style != BraceStyle::AlwaysNextLine)
2968                 || trimmed_last_line_width(&result) == 1,
2969             rewrite_missing_comment(
2970                 mk_sp(
2971                     span_end_before_where,
2972                     if brace_pos == BracePos::None {
2973                         span.hi()
2974                     } else {
2975                         context.snippet_provider.span_before(span, "{")
2976                     },
2977                 ),
2978                 shape,
2979                 context,
2980             ),
2981         )
2982     };
2983     // add missing comments
2984     let missed_line_comments = missed_comments
2985         .filter(|missed_comments| !missed_comments.is_empty())
2986         .map_or(false, |missed_comments| {
2987             let is_block = is_last_comment_block(&missed_comments);
2988             let sep = if is_block { " " } else { "\n" };
2989             result.push_str(sep);
2990             result.push_str(&missed_comments);
2991             !is_block
2992         });
2993     if brace_pos == BracePos::None {
2994         return Some(result);
2995     }
2996     let total_used_width = last_line_used_width(&result, used_width);
2997     let remaining_budget = context.budget(total_used_width);
2998     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2999     // and hence we take the closer into account as well for one line budget.
3000     // We assume that the closer has the same length as the opener.
3001     let overhead = if brace_pos == BracePos::ForceSameLine {
3002         // 3 = ` {}`
3003         3
3004     } else {
3005         // 2 = ` {`
3006         2
3007     };
3008     let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3009     if !forbid_same_line_brace && same_line_brace {
3010         result.push(' ');
3011     } else {
3012         result.push('\n');
3013         result.push_str(&offset.block_only().to_string(context.config));
3014     }
3015     result.push('{');
3016
3017     Some(result)
3018 }
3019
3020 impl Rewrite for ast::ForeignItem {
3021     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3022         let attrs_str = self.attrs.rewrite(context, shape)?;
3023         // Drop semicolon or it will be interpreted as comment.
3024         // FIXME: this may be a faulty span from libsyntax.
3025         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3026
3027         let item_str = match self.kind {
3028             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
3029                 context,
3030                 shape.indent,
3031                 self.ident,
3032                 &FnSig::new(fn_decl, generics, self.vis.clone()),
3033                 span,
3034                 FnBraceStyle::None,
3035             )
3036             .map(|(s, _)| format!("{};", s)),
3037             ast::ForeignItemKind::Static(ref ty, mutability) => {
3038                 // FIXME(#21): we're dropping potential comments in between the
3039                 // function kw here.
3040                 let vis = format_visibility(context, &self.vis);
3041                 let mut_str = format_mutability(mutability);
3042                 let prefix = format!(
3043                     "{}static {}{}:",
3044                     vis,
3045                     mut_str,
3046                     rewrite_ident(context, self.ident)
3047                 );
3048                 // 1 = ;
3049                 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
3050             }
3051             ast::ForeignItemKind::Ty => {
3052                 let vis = format_visibility(context, &self.vis);
3053                 Some(format!(
3054                     "{}type {};",
3055                     vis,
3056                     rewrite_ident(context, self.ident)
3057                 ))
3058             }
3059             ast::ForeignItemKind::Macro(ref mac) => {
3060                 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
3061             }
3062         }?;
3063
3064         let missing_span = if self.attrs.is_empty() {
3065             mk_sp(self.span.lo(), self.span.lo())
3066         } else {
3067             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3068         };
3069         combine_strs_with_missing_comments(
3070             context,
3071             &attrs_str,
3072             &item_str,
3073             missing_span,
3074             shape,
3075             false,
3076         )
3077     }
3078 }
3079
3080 /// Rewrite the attributes of an item.
3081 fn rewrite_attrs(
3082     context: &RewriteContext<'_>,
3083     item: &ast::Item,
3084     item_str: &str,
3085     shape: Shape,
3086 ) -> Option<String> {
3087     let attrs = filter_inline_attrs(&item.attrs, item.span());
3088     let attrs_str = attrs.rewrite(context, shape)?;
3089
3090     let missed_span = if attrs.is_empty() {
3091         mk_sp(item.span.lo(), item.span.lo())
3092     } else {
3093         mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3094     };
3095
3096     let allow_extend = if attrs.len() == 1 {
3097         let line_len = attrs_str.len() + 1 + item_str.len();
3098         !attrs.first().unwrap().is_sugared_doc
3099             && context.config.inline_attribute_width() >= line_len
3100     } else {
3101         false
3102     };
3103
3104     combine_strs_with_missing_comments(
3105         context,
3106         &attrs_str,
3107         &item_str,
3108         missed_span,
3109         shape,
3110         allow_extend,
3111     )
3112 }
3113
3114 /// Rewrite an inline mod.
3115 /// The given shape is used to format the mod's attributes.
3116 pub(crate) fn rewrite_mod(
3117     context: &RewriteContext<'_>,
3118     item: &ast::Item,
3119     attrs_shape: Shape,
3120 ) -> Option<String> {
3121     let mut result = String::with_capacity(32);
3122     result.push_str(&*format_visibility(context, &item.vis));
3123     result.push_str("mod ");
3124     result.push_str(rewrite_ident(context, item.ident));
3125     result.push(';');
3126     rewrite_attrs(context, item, &result, attrs_shape)
3127 }
3128
3129 /// Rewrite `extern crate foo;`.
3130 /// The given shape is used to format the extern crate's attributes.
3131 pub(crate) fn rewrite_extern_crate(
3132     context: &RewriteContext<'_>,
3133     item: &ast::Item,
3134     attrs_shape: Shape,
3135 ) -> Option<String> {
3136     assert!(is_extern_crate(item));
3137     let new_str = context.snippet(item.span);
3138     let item_str = if contains_comment(new_str) {
3139         new_str.to_owned()
3140     } else {
3141         let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3142         String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3143     };
3144     rewrite_attrs(context, item, &item_str, attrs_shape)
3145 }
3146
3147 /// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3148 pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3149     match item.kind {
3150         ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
3151         _ => false,
3152     }
3153 }
3154
3155 pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3156     match item.kind {
3157         ast::ItemKind::Use(_) => true,
3158         _ => false,
3159     }
3160 }
3161
3162 pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3163     match item.kind {
3164         ast::ItemKind::ExternCrate(..) => true,
3165         _ => false,
3166     }
3167 }