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