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