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