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