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