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