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