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