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