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