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