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