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