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