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