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