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