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