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