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