]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Small reformat
[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 {Indent, Shape};
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16             last_line_width, format_unsafety, trim_newlines, stmt_expr, semicolon_for_expr};
17 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
18             DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
19 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, type_annotation_separator};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use itertools::Itertools;
25
26 use syntax::{ast, abi, codemap, ptr, symbol};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::ast::ImplItem;
29
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
34         debug!("Local::rewrite {:?} {} {:?}",
35                self,
36                shape.width,
37                shape.indent);
38         let mut result = "let ".to_owned();
39         let pattern_offset = shape.indent + result.len();
40         // 1 = ;
41         let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
42
43         let pat_str = try_opt!(self.pat
44                                    .rewrite(&context,
45                                             Shape::legacy(pattern_width, pattern_offset)));
46         result.push_str(&pat_str);
47
48         // String that is placed within the assignment pattern and expression.
49         let infix = {
50             let mut infix = String::new();
51
52             if let Some(ref ty) = self.ty {
53                 let separator = type_annotation_separator(context.config);
54                 let indent = shape.indent + last_line_width(&result) + separator.len();
55                 // 1 = ;
56                 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
57                 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
58
59                 infix.push_str(separator);
60                 infix.push_str(&rewrite);
61             }
62
63             if self.init.is_some() {
64                 infix.push_str(" =");
65             }
66
67             infix
68         };
69
70         result.push_str(&infix);
71
72         if let Some(ref ex) = self.init {
73             // 1 = trailing semicolon;
74             let budget = try_opt!(shape.width.checked_sub(shape.indent.block_only().width() + 1));
75
76             result = try_opt!(rewrite_assign_rhs(&context,
77                                                  result,
78                                                  ex,
79                                                  Shape::legacy(budget, shape.indent.block_only())));
80         }
81
82         result.push(';');
83         Some(result)
84     }
85 }
86
87 // TODO convert to using rewrite style rather than visitor
88 // TODO format modules in this style
89 #[allow(dead_code)]
90 struct Item<'a> {
91     keyword: &'static str,
92     abi: String,
93     vis: Option<&'a ast::Visibility>,
94     body: Vec<BodyElement<'a>>,
95     span: Span,
96 }
97
98 impl<'a> Item<'a> {
99     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
100         let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi {
101             "extern".into()
102         } else {
103             format!("extern {}", fm.abi)
104         };
105         Item {
106             keyword: "",
107             abi: abi,
108             vis: None,
109             body: fm.items.iter().map(|i| BodyElement::ForeignItem(i)).collect(),
110             span: span,
111         }
112     }
113 }
114
115 enum BodyElement<'a> {
116     // Stmt(&'a ast::Stmt),
117     // Field(&'a ast::Field),
118     // Variant(&'a ast::Variant),
119     // Item(&'a ast::Item),
120     ForeignItem(&'a ast::ForeignItem),
121 }
122
123 impl<'a> FmtVisitor<'a> {
124     fn format_item(&mut self, item: Item) {
125         self.buffer.push_str(&item.abi);
126         self.buffer.push_str(" ");
127
128         let snippet = self.snippet(item.span);
129         let brace_pos = snippet.find_uncommented("{").unwrap();
130
131         self.buffer.push_str("{");
132         if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
133             // FIXME: this skips comments between the extern keyword and the opening
134             // brace.
135             self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
136             self.block_indent = self.block_indent.block_indent(self.config);
137
138             if item.body.is_empty() {
139                 self.format_missing_no_indent(item.span.hi - BytePos(1));
140                 self.block_indent = self.block_indent.block_unindent(self.config);
141
142                 self.buffer.push_str(&self.block_indent.to_string(self.config));
143             } else {
144                 for item in &item.body {
145                     self.format_body_element(item);
146                 }
147
148                 self.block_indent = self.block_indent.block_unindent(self.config);
149                 self.format_missing_with_indent(item.span.hi - BytePos(1));
150             }
151         }
152
153         self.buffer.push_str("}");
154         self.last_pos = item.span.hi;
155     }
156
157     fn format_body_element(&mut self, element: &BodyElement) {
158         match *element {
159             BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
160         }
161     }
162
163     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
164         let item = Item::from_foreign_mod(fm, span, self.config);
165         self.format_item(item);
166     }
167
168     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
169         self.format_missing_with_indent(item.span.lo);
170         // Drop semicolon or it will be interpreted as comment.
171         // FIXME: this may be a faulty span from libsyntax.
172         let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
173
174         match item.node {
175             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
176                 let indent = self.block_indent;
177                 let rewrite = rewrite_fn_base(&self.get_context(),
178                                               indent,
179                                               item.ident,
180                                               fn_decl,
181                                               generics,
182                                               ast::Unsafety::Normal,
183                                               ast::Constness::NotConst,
184                                               ast::Defaultness::Final,
185                                               // These are not actually rust functions,
186                                               // but we format them as such.
187                                               abi::Abi::Rust,
188                                               &item.vis,
189                                               span,
190                                               false,
191                                               false);
192
193                 match rewrite {
194                     Some((new_fn, _)) => {
195                         self.buffer.push_str(&new_fn);
196                         self.buffer.push_str(";");
197                     }
198                     None => self.format_missing(item.span.hi),
199                 }
200             }
201             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
202                 // FIXME(#21): we're dropping potential comments in between the
203                 // function keywords here.
204                 let vis = format_visibility(&item.vis);
205                 let mut_str = if is_mutable { "mut " } else { "" };
206                 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
207                 let offset = self.block_indent + prefix.len();
208                 // 1 = ;
209                 let width = self.config.max_width - offset.width() - 1;
210                 let rewrite = ty.rewrite(&self.get_context(), Shape::legacy(width, offset));
211
212                 match rewrite {
213                     Some(result) => {
214                         self.buffer.push_str(&prefix);
215                         self.buffer.push_str(&result);
216                         self.buffer.push_str(";");
217                     }
218                     None => self.format_missing(item.span.hi),
219                 }
220             }
221         }
222
223         self.last_pos = item.span.hi;
224     }
225
226     pub fn rewrite_fn(&mut self,
227                       indent: Indent,
228                       ident: ast::Ident,
229                       fd: &ast::FnDecl,
230                       generics: &ast::Generics,
231                       unsafety: ast::Unsafety,
232                       constness: ast::Constness,
233                       defaultness: ast::Defaultness,
234                       abi: abi::Abi,
235                       vis: &ast::Visibility,
236                       span: Span,
237                       block: &ast::Block)
238                       -> Option<String> {
239         let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
240         let context = self.get_context();
241
242         let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
243         let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
244                        !context.config.fn_empty_single_line;
245
246         let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
247                                                                          indent,
248                                                                          ident,
249                                                                          fd,
250                                                                          generics,
251                                                                          unsafety,
252                                                                          constness,
253                                                                          defaultness,
254                                                                          abi,
255                                                                          vis,
256                                                                          span,
257                                                                          newline_brace,
258                                                                          has_body));
259
260         if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
261             newline_brace = false;
262         } else if force_newline_brace {
263             newline_brace = true;
264         }
265
266         // Prepare for the function body by possibly adding a newline and
267         // indent.
268         // FIXME we'll miss anything between the end of the signature and the
269         // start of the body, but we need more spans from the compiler to solve
270         // this.
271         if newline_brace {
272             result.push('\n');
273             result.push_str(&indent.to_string(self.config));
274         } else {
275             result.push(' ');
276         }
277
278         self.single_line_fn(&result, block).or_else(|| Some(result))
279     }
280
281     pub fn rewrite_required_fn(&mut self,
282                                indent: Indent,
283                                ident: ast::Ident,
284                                sig: &ast::MethodSig,
285                                span: Span)
286                                -> Option<String> {
287         // Drop semicolon or it will be interpreted as comment.
288         let span = mk_sp(span.lo, span.hi - BytePos(1));
289         let context = self.get_context();
290
291         let (mut result, _) = try_opt!(rewrite_fn_base(&context,
292                                                        indent,
293                                                        ident,
294                                                        &sig.decl,
295                                                        &sig.generics,
296                                                        sig.unsafety,
297                                                        sig.constness.node,
298                                                        ast::Defaultness::Final,
299                                                        sig.abi,
300                                                        &ast::Visibility::Inherited,
301                                                        span,
302                                                        false,
303                                                        false));
304
305         // Re-attach semicolon
306         result.push(';');
307
308         Some(result)
309     }
310
311     fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
312         if fn_str.contains('\n') {
313             return None;
314         }
315
316         let codemap = self.get_context().codemap;
317
318         if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
319            self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
320             return Some(format!("{}{{}}", fn_str));
321         }
322
323         if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
324             let rewrite = {
325                 if let Some(ref stmt) = block.stmts.first() {
326                     match stmt_expr(stmt) {
327                         Some(e) => {
328                             let suffix = if semicolon_for_expr(e) { ";" } else { "" };
329
330                             e.rewrite(&self.get_context(),
331                                          Shape::legacy(self.config.max_width -
332                                                        self.block_indent.width(),
333                                                        self.block_indent))
334                                 .map(|s| s + suffix)
335                                 .or_else(|| Some(self.snippet(e.span)))
336                         }
337                         None => {
338                             stmt.rewrite(&self.get_context(),
339                                          Shape::legacy(self.config.max_width -
340                                                        self.block_indent.width(),
341                                                        self.block_indent))
342                         }
343                     }
344                 } else {
345                     None
346                 }
347             };
348
349             if let Some(res) = rewrite {
350                 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
351                 if !res.contains('\n') && width <= self.config.max_width {
352                     return Some(format!("{}{{ {} }}", fn_str, res));
353                 }
354             }
355         }
356
357         None
358     }
359
360     pub fn visit_enum(&mut self,
361                       ident: ast::Ident,
362                       vis: &ast::Visibility,
363                       enum_def: &ast::EnumDef,
364                       generics: &ast::Generics,
365                       span: Span) {
366         self.buffer.push_str(&format_header("enum ", ident, vis));
367
368         let enum_snippet = self.snippet(span);
369         let brace_pos = enum_snippet.find_uncommented("{").unwrap();
370         let body_start = span.lo + BytePos(brace_pos as u32 + 1);
371         let generics_str = format_generics(&self.get_context(),
372                                            generics,
373                                            "{",
374                                            "{",
375                                            self.config.item_brace_style,
376                                            enum_def.variants.is_empty(),
377                                            self.block_indent,
378                                            self.block_indent.block_indent(self.config),
379                                            mk_sp(span.lo, body_start))
380                 .unwrap();
381         self.buffer.push_str(&generics_str);
382
383         self.last_pos = body_start;
384
385         self.block_indent = self.block_indent.block_indent(self.config);
386         let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
387         match variant_list {
388             Some(ref body_str) => self.buffer.push_str(body_str),
389             None => {
390                 if contains_comment(&enum_snippet[brace_pos..]) {
391                     self.format_missing_no_indent(span.hi - BytePos(1))
392                 } else {
393                     self.format_missing(span.hi - BytePos(1))
394                 }
395             }
396         }
397         self.block_indent = self.block_indent.block_unindent(self.config);
398
399         if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
400             self.buffer.push_str(&self.block_indent.to_string(self.config));
401         }
402         self.buffer.push_str("}");
403         self.last_pos = span.hi;
404     }
405
406     // Format the body of an enum definition
407     fn format_variant_list(&self,
408                            enum_def: &ast::EnumDef,
409                            body_lo: BytePos,
410                            body_hi: BytePos)
411                            -> Option<String> {
412         if enum_def.variants.is_empty() {
413             return None;
414         }
415         let mut result = String::with_capacity(1024);
416         result.push('\n');
417         let indentation = self.block_indent.to_string(self.config);
418         result.push_str(&indentation);
419
420         let items = itemize_list(self.codemap,
421                                  enum_def.variants.iter(),
422                                  "}",
423                                  |f| if !f.node.attrs.is_empty() {
424                                      f.node.attrs[0].span.lo
425                                  } else {
426                                      f.span.lo
427                                  },
428                                  |f| f.span.hi,
429                                  |f| self.format_variant(f),
430                                  body_lo,
431                                  body_hi);
432
433         let budget = self.config.max_width - self.block_indent.width() - 2;
434         let fmt = ListFormatting {
435             tactic: DefinitiveListTactic::Vertical,
436             separator: ",",
437             trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
438             shape: Shape::legacy(budget, self.block_indent),
439             ends_with_newline: true,
440             config: self.config,
441         };
442
443         let list = try_opt!(write_list(items, &fmt));
444         result.push_str(&list);
445         result.push('\n');
446         Some(result)
447     }
448
449     // Variant of an enum.
450     fn format_variant(&self, field: &ast::Variant) -> Option<String> {
451         if contains_skip(&field.node.attrs) {
452             let lo = field.node.attrs[0].span.lo;
453             let span = mk_sp(lo, field.span.hi);
454             return Some(self.snippet(span));
455         }
456
457         let indent = self.block_indent;
458         let mut result = try_opt!(field.node
459                                       .attrs
460                                       .rewrite(&self.get_context(),
461                                                Shape::legacy(self.config.max_width -
462                                                              indent.width(),
463                                                              indent)));
464         if !result.is_empty() {
465             result.push('\n');
466             result.push_str(&indent.to_string(self.config));
467         }
468
469         let context = self.get_context();
470         let variant_body = match field.node.data {
471             ast::VariantData::Tuple(..) |
472             ast::VariantData::Struct(..) => {
473                 // FIXME: Should limit the width, as we have a trailing comma
474                 format_struct(&context,
475                               "",
476                               field.node.name,
477                               &ast::Visibility::Inherited,
478                               &field.node.data,
479                               None,
480                               field.span,
481                               indent,
482                               Some(self.config.struct_variant_width))
483             }
484             ast::VariantData::Unit(..) => {
485                 let tag = if let Some(ref expr) = field.node.disr_expr {
486                     format!("{} = {}", field.node.name, self.snippet(expr.span))
487                 } else {
488                     field.node.name.to_string()
489                 };
490
491                 wrap_str(tag,
492                          self.config.max_width,
493                          Shape::legacy(self.config.max_width - indent.width(), indent))
494             }
495         };
496
497         if let Some(variant_str) = variant_body {
498             result.push_str(&variant_str);
499             Some(result)
500         } else {
501             None
502         }
503     }
504 }
505
506 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
507     if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
508         let mut result = String::new();
509         // First try to format the ref and type without a split at the 'for'.
510         let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
511
512         // If there is a line break present in the first result format it again
513         // with a split at the 'for'. Skip this if there is no trait ref and
514         // therefore no 'for'.
515         if ref_and_type.contains('\n') && trait_ref.is_some() {
516             ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
517         }
518         result.push_str(&ref_and_type);
519
520         let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
521         let where_clause_str = try_opt!(rewrite_where_clause(context,
522                                                              &generics.where_clause,
523                                                              context.config,
524                                                              context.config.item_brace_style,
525                                                              Shape::legacy(where_budget,
526                                                                            offset.block_only()),
527                                                              context.config.where_density,
528                                                              "{",
529                                                              true,
530                                                              None));
531
532         if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
533             result.push_str(&where_clause_str);
534             if where_clause_str.contains('\n') {
535                 let white_space = offset.to_string(context.config);
536                 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
537             } else {
538                 result.push_str(" {}");
539             }
540             return Some(result);
541         }
542
543         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
544             result.push('\n');
545             let width = offset.block_indent + context.config.tab_spaces - 1;
546             let where_indent = Indent::new(0, width);
547             result.push_str(&where_indent.to_string(context.config));
548         }
549         result.push_str(&where_clause_str);
550
551         match context.config.item_brace_style {
552             BraceStyle::AlwaysNextLine => {
553                 result.push('\n');
554                 result.push_str(&offset.to_string(context.config));
555             }
556             BraceStyle::PreferSameLine => result.push(' '),
557             BraceStyle::SameLineWhere => {
558                 if !where_clause_str.is_empty() {
559                     result.push('\n');
560                     result.push_str(&offset.to_string(context.config));
561                 } else {
562                     result.push(' ');
563                 }
564             }
565         }
566
567         result.push('{');
568
569         let snippet = context.snippet(item.span);
570         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
571
572         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
573             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
574             visitor.block_indent = offset.block_only().block_indent(context.config);
575             visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
576
577             for item in items {
578                 visitor.visit_impl_item(item);
579             }
580
581             visitor.format_missing(item.span.hi - BytePos(1));
582
583             let inner_indent_str = visitor.block_indent.to_string(context.config);
584             let outer_indent_str = offset.block_only().to_string(context.config);
585
586             result.push('\n');
587             result.push_str(&inner_indent_str);
588             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
589             result.push('\n');
590             result.push_str(&outer_indent_str);
591         }
592
593         if result.chars().last().unwrap() == '{' {
594             result.push('\n');
595             result.push_str(&offset.to_string(context.config));
596         }
597         result.push('}');
598
599         Some(result)
600     } else {
601         unreachable!();
602     }
603 }
604
605 fn is_impl_single_line(context: &RewriteContext,
606                        items: &[ImplItem],
607                        result: &str,
608                        where_clause_str: &str,
609                        item: &ast::Item)
610                        -> Option<bool> {
611     let snippet = context.snippet(item.span);
612     let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
613
614     Some(context.config.impl_empty_single_line && items.is_empty() &&
615          result.len() + where_clause_str.len() <= context.config.max_width &&
616          !contains_comment(&snippet[open_pos..]))
617 }
618
619 fn format_impl_ref_and_type(context: &RewriteContext,
620                             item: &ast::Item,
621                             offset: Indent,
622                             split_at_for: bool)
623                             -> Option<String> {
624     if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
625         item.node {
626         let mut result = String::new();
627
628         result.push_str(&*format_visibility(&item.vis));
629         result.push_str(format_unsafety(unsafety));
630         result.push_str("impl");
631
632         let lo = context.codemap.span_after(item.span, "impl");
633         let hi = match *trait_ref {
634             Some(ref tr) => tr.path.span.lo,
635             None => self_ty.span.lo,
636         };
637         let generics_str = try_opt!(rewrite_generics(context,
638                                                      generics,
639                                                      Shape::legacy(context.config.max_width,
640                                                                    offset),
641                                                      offset + result.len(),
642                                                      mk_sp(lo, hi)));
643         result.push_str(&generics_str);
644
645         if polarity == ast::ImplPolarity::Negative {
646             result.push_str(" !");
647         }
648         if let Some(ref trait_ref) = *trait_ref {
649             if polarity != ast::ImplPolarity::Negative {
650                 result.push_str(" ");
651             }
652             let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
653             let indent = offset + result.len();
654             result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
655
656             if split_at_for {
657                 result.push('\n');
658
659                 // Add indentation of one additional tab.
660                 let width = offset.block_indent + context.config.tab_spaces;
661                 let for_indent = Indent::new(0, width);
662                 result.push_str(&for_indent.to_string(context.config));
663
664                 result.push_str("for");
665             } else {
666                 result.push_str(" for");
667             }
668         }
669
670         let mut used_space = last_line_width(&result);
671         if generics.where_clause.predicates.is_empty() {
672             // If there is no where clause adapt budget for type formatting to take space and curly
673             // brace into account.
674             match context.config.item_brace_style {
675                 BraceStyle::AlwaysNextLine => {}
676                 BraceStyle::PreferSameLine => used_space += 2,
677                 BraceStyle::SameLineWhere => used_space += 2,
678             }
679         }
680
681         // 1 = space before the type.
682         let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1));
683         let indent = offset + result.len() + 1;
684         let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
685         if let Some(self_ty_str) = self_ty_str {
686             result.push_str(" ");
687             result.push_str(&self_ty_str);
688             return Some(result);
689         }
690
691         // Can't fit the self type on what's left of the line, so start a new one.
692         let indent = offset.block_indent(context.config);
693         result.push_str(&format!("\n{}", indent.to_string(context.config)));
694         let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
695         result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
696         Some(result)
697     } else {
698         unreachable!();
699     }
700 }
701
702 pub fn format_struct(context: &RewriteContext,
703                      item_name: &str,
704                      ident: ast::Ident,
705                      vis: &ast::Visibility,
706                      struct_def: &ast::VariantData,
707                      generics: Option<&ast::Generics>,
708                      span: Span,
709                      offset: Indent,
710                      one_line_width: Option<usize>)
711                      -> Option<String> {
712     match *struct_def {
713         ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
714         ast::VariantData::Tuple(ref fields, _) => {
715             format_tuple_struct(context,
716                                 item_name,
717                                 ident,
718                                 vis,
719                                 fields,
720                                 generics,
721                                 span,
722                                 offset)
723         }
724         ast::VariantData::Struct(ref fields, _) => {
725             format_struct_struct(context,
726                                  item_name,
727                                  ident,
728                                  vis,
729                                  fields,
730                                  generics,
731                                  span,
732                                  offset,
733                                  one_line_width)
734         }
735     }
736 }
737
738 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
739     if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
740         item.node {
741         let mut result = String::new();
742         let header = format!("{}{}trait {}",
743                              format_visibility(&item.vis),
744                              format_unsafety(unsafety),
745                              item.ident);
746
747         result.push_str(&header);
748
749         let body_lo = context.codemap.span_after(item.span, "{");
750
751         let generics_str = try_opt!(rewrite_generics(context,
752                                                      generics,
753                                                      Shape::legacy(context.config.max_width,
754                                                                    offset),
755                                                      offset + result.len(),
756                                                      mk_sp(item.span.lo, body_lo)));
757         result.push_str(&generics_str);
758
759         let trait_bound_str =
760             try_opt!(rewrite_trait_bounds(context,
761                                           type_param_bounds,
762                                           Shape::legacy(context.config.max_width, offset)));
763         // If the trait, generics, and trait bound cannot fit on the same line,
764         // put the trait bounds on an indented new line
765         if offset.width() + last_line_width(&result) + trait_bound_str.len() >
766            context.config.ideal_width {
767             result.push('\n');
768             let trait_indent = offset.block_only().block_indent(context.config);
769             result.push_str(&trait_indent.to_string(context.config));
770         }
771         result.push_str(&trait_bound_str);
772
773         let has_body = !trait_items.is_empty();
774
775         let where_density =
776             if (context.config.where_density == Density::Compressed &&
777                 (!result.contains('\n') ||
778                  context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
779                (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
780                (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
781                 !result.contains('\n')) {
782                 Density::Compressed
783             } else {
784                 Density::Tall
785             };
786
787         let where_budget = try_opt!(context.config
788                                         .max_width
789                                         .checked_sub(last_line_width(&result)));
790         let where_clause_str = try_opt!(rewrite_where_clause(context,
791                                                              &generics.where_clause,
792                                                              context.config,
793                                                              context.config.item_brace_style,
794                                                              Shape::legacy(where_budget,
795                                                                            offset.block_only()),
796                                                              where_density,
797                                                              "{",
798                                                              has_body,
799                                                              None));
800         // If the where clause cannot fit on the same line,
801         // put the where clause on a new line
802         if !where_clause_str.contains('\n') &&
803            last_line_width(&result) + where_clause_str.len() + offset.width() >
804            context.config.ideal_width {
805             result.push('\n');
806             let width = offset.block_indent + context.config.tab_spaces - 1;
807             let where_indent = Indent::new(0, width);
808             result.push_str(&where_indent.to_string(context.config));
809         }
810         result.push_str(&where_clause_str);
811
812         match context.config.item_brace_style {
813             BraceStyle::AlwaysNextLine => {
814                 result.push('\n');
815                 result.push_str(&offset.to_string(context.config));
816             }
817             BraceStyle::PreferSameLine => result.push(' '),
818             BraceStyle::SameLineWhere => {
819                 if !where_clause_str.is_empty() &&
820                    (!trait_items.is_empty() || result.contains('\n')) {
821                     result.push('\n');
822                     result.push_str(&offset.to_string(context.config));
823                 } else {
824                     result.push(' ');
825                 }
826             }
827         }
828         result.push('{');
829
830         let snippet = context.snippet(item.span);
831         let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
832
833         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
834             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
835             visitor.block_indent = offset.block_only().block_indent(context.config);
836             visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
837
838             for item in trait_items {
839                 visitor.visit_trait_item(item);
840             }
841
842             visitor.format_missing(item.span.hi - BytePos(1));
843
844             let inner_indent_str = visitor.block_indent.to_string(context.config);
845             let outer_indent_str = offset.block_only().to_string(context.config);
846
847             result.push('\n');
848             result.push_str(&inner_indent_str);
849             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
850             result.push('\n');
851             result.push_str(&outer_indent_str);
852         } else if result.contains('\n') {
853             result.push('\n');
854         }
855
856         result.push('}');
857         Some(result)
858     } else {
859         unreachable!();
860     }
861 }
862
863 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
864     format!("{};", format_header(item_name, ident, vis))
865 }
866
867 fn format_struct_struct(context: &RewriteContext,
868                         item_name: &str,
869                         ident: ast::Ident,
870                         vis: &ast::Visibility,
871                         fields: &[ast::StructField],
872                         generics: Option<&ast::Generics>,
873                         span: Span,
874                         offset: Indent,
875                         one_line_width: Option<usize>)
876                         -> Option<String> {
877     let mut result = String::with_capacity(1024);
878
879     let header_str = format_header(item_name, ident, vis);
880     result.push_str(&header_str);
881
882     let body_lo = context.codemap.span_after(span, "{");
883
884     let generics_str = match generics {
885         Some(g) => {
886             try_opt!(format_generics(context,
887                                      g,
888                                      "{",
889                                      "{",
890                                      context.config.item_brace_style,
891                                      fields.is_empty(),
892                                      offset,
893                                      offset + header_str.len(),
894                                      mk_sp(span.lo, body_lo)))
895         }
896         None => {
897             if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
898                 format!("\n{}{{", offset.block_only().to_string(context.config))
899             } else {
900                 " {".to_owned()
901             }
902         }
903     };
904     result.push_str(&generics_str);
905
906     // FIXME(#919): properly format empty structs and their comments.
907     if fields.is_empty() {
908         let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
909         if snippet.trim().is_empty() {
910             // `struct S {}`
911         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
912             // fix indent
913             result.push_str(&snippet.trim_right());
914             result.push('\n');
915             result.push_str(&offset.to_string(context.config));
916         } else {
917             result.push_str(&snippet);
918         }
919         result.push('}');
920         return Some(result);
921     }
922
923     let item_indent = offset.block_indent(context.config);
924     // 1 = ","
925     let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
926
927     let items =
928         itemize_list(context.codemap,
929                      fields.iter(),
930                      "}",
931                      |field| {
932             // Include attributes and doc comments, if present
933             if !field.attrs.is_empty() {
934                 field.attrs[0].span.lo
935             } else {
936                 field.span.lo
937             }
938         },
939                      |field| field.ty.span.hi,
940                      |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
941                      context.codemap.span_after(span, "{"),
942                      span.hi)
943                 .collect::<Vec<_>>();
944     // 1 = ,
945     let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
946
947     let tactic = match one_line_width {
948         Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
949         None => DefinitiveListTactic::Vertical,
950     };
951
952     let fmt = ListFormatting {
953         tactic: tactic,
954         separator: ",",
955         trailing_separator: context.config.struct_trailing_comma,
956         shape: Shape::legacy(budget, item_indent),
957         ends_with_newline: true,
958         config: context.config,
959     };
960     let items_str = try_opt!(write_list(&items, &fmt));
961     if one_line_width.is_some() && !items_str.contains('\n') {
962         Some(format!("{} {} }}", result, items_str))
963     } else {
964         Some(format!("{}\n{}{}\n{}}}",
965                      result,
966                      offset.block_indent(context.config).to_string(context.config),
967                      items_str,
968                      offset.to_string(context.config)))
969     }
970 }
971
972 fn format_tuple_struct(context: &RewriteContext,
973                        item_name: &str,
974                        ident: ast::Ident,
975                        vis: &ast::Visibility,
976                        fields: &[ast::StructField],
977                        generics: Option<&ast::Generics>,
978                        span: Span,
979                        offset: Indent)
980                        -> Option<String> {
981     let mut result = String::with_capacity(1024);
982
983     let header_str = format_header(item_name, ident, vis);
984     result.push_str(&header_str);
985
986     // FIXME(#919): don't lose comments on empty tuple structs.
987     let body_lo = if fields.is_empty() {
988         span.hi
989     } else {
990         fields[0].span.lo
991     };
992
993     let where_clause_str = match generics {
994         Some(generics) => {
995             let generics_str = try_opt!(rewrite_generics(context,
996                                                          generics,
997                                                          Shape::legacy(context.config.max_width,
998                                                                        offset),
999                                                          offset + header_str.len(),
1000                                                          mk_sp(span.lo, body_lo)));
1001             result.push_str(&generics_str);
1002
1003             let where_budget = try_opt!(context.config
1004                                             .max_width
1005                                             .checked_sub(last_line_width(&result)));
1006             try_opt!(rewrite_where_clause(context,
1007                                           &generics.where_clause,
1008                                           context.config,
1009                                           context.config.item_brace_style,
1010                                           Shape::legacy(where_budget, offset.block_only()),
1011                                           Density::Compressed,
1012                                           ";",
1013                                           false,
1014                                           None))
1015         }
1016         None => "".to_owned(),
1017     };
1018     result.push('(');
1019
1020     let item_indent = offset.block_only() + result.len();
1021     // 2 = ");"
1022     let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
1023
1024     let items =
1025         itemize_list(context.codemap,
1026                      fields.iter(),
1027                      ")",
1028                      |field| {
1029             // Include attributes and doc comments, if present
1030             if !field.attrs.is_empty() {
1031                 field.attrs[0].span.lo
1032             } else {
1033                 field.span.lo
1034             }
1035         },
1036                      |field| field.ty.span.hi,
1037                      |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1038                      context.codemap.span_after(span, "("),
1039                      span.hi);
1040     let body = try_opt!(format_item_list(items,
1041                                          Shape::legacy(item_budget, item_indent),
1042                                          context.config));
1043
1044     if context.config.spaces_within_parens && body.len() > 0 {
1045         result.push(' ');
1046     }
1047
1048     result.push_str(&body);
1049
1050     if context.config.spaces_within_parens && body.len() > 0 {
1051         result.push(' ');
1052     }
1053
1054     result.push(')');
1055
1056     if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1057        (result.contains('\n') ||
1058         offset.block_indent + result.len() + where_clause_str.len() + 1 >
1059         context.config.max_width) {
1060         // We need to put the where clause on a new line, but we didn'to_string
1061         // know that earlier, so the where clause will not be indented properly.
1062         result.push('\n');
1063         result.push_str(&(offset.block_only() + (context.config.tab_spaces - 1))
1064                              .to_string(context.config));
1065     }
1066     result.push_str(&where_clause_str);
1067
1068     Some(result)
1069 }
1070
1071 pub fn rewrite_type_alias(context: &RewriteContext,
1072                           indent: Indent,
1073                           ident: ast::Ident,
1074                           ty: &ast::Ty,
1075                           generics: &ast::Generics,
1076                           vis: &ast::Visibility,
1077                           span: Span)
1078                           -> Option<String> {
1079     let mut result = String::new();
1080
1081     result.push_str(&format_visibility(vis));
1082     result.push_str("type ");
1083     result.push_str(&ident.to_string());
1084
1085     let generics_indent = indent + result.len();
1086     let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1087     let generics_width = context.config.max_width - " =".len();
1088     let generics_str = try_opt!(rewrite_generics(context,
1089                                                  generics,
1090                                                  Shape::legacy(generics_width, indent),
1091                                                  generics_indent,
1092                                                  generics_span));
1093
1094     result.push_str(&generics_str);
1095
1096     let where_budget = try_opt!(context.config
1097                                     .max_width
1098                                     .checked_sub(last_line_width(&result)));
1099     let where_clause_str = try_opt!(rewrite_where_clause(context,
1100                                                          &generics.where_clause,
1101                                                          context.config,
1102                                                          context.config.item_brace_style,
1103                                                          Shape::legacy(where_budget, indent),
1104                                                          context.config.where_density,
1105                                                          "=",
1106                                                          false,
1107                                                          Some(span.hi)));
1108     result.push_str(&where_clause_str);
1109     result.push_str(" = ");
1110
1111     let line_width = last_line_width(&result);
1112     // This checked_sub may fail as the extra space after '=' is not taken into account
1113     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1114     let budget = context.config
1115         .max_width
1116         .checked_sub(indent.width() + line_width + ";".len())
1117         .unwrap_or(0);
1118     let type_indent = indent + line_width;
1119     // Try to fit the type on the same line
1120     let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
1121                               .or_else(|| {
1122         // The line was too short, try to put the type on the next line
1123
1124         // Remove the space after '='
1125         result.pop();
1126         let type_indent = indent.block_indent(context.config);
1127         result.push('\n');
1128         result.push_str(&type_indent.to_string(context.config));
1129         let budget = try_opt!(context.config
1130                                   .max_width
1131                                   .checked_sub(type_indent.width() + ";".len()));
1132         ty.rewrite(context, Shape::legacy(budget, type_indent))
1133     }));
1134     result.push_str(&ty_str);
1135     result.push_str(";");
1136     Some(result)
1137 }
1138
1139 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1140     (if config.space_before_type_annotation {
1141          " "
1142      } else {
1143          ""
1144      },
1145      if config.space_after_type_annotation_colon {
1146          " "
1147      } else {
1148          ""
1149      })
1150 }
1151
1152 impl Rewrite for ast::StructField {
1153     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1154         if contains_skip(&self.attrs) {
1155             let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1156             return wrap_str(span, context.config.max_width, shape);
1157         }
1158
1159         let name = self.ident;
1160         let vis = format_visibility(&self.vis);
1161         let mut attr_str = try_opt!(self.attrs
1162                                         .rewrite(context,
1163                                                  Shape::legacy(context.config.max_width -
1164                                                                shape.indent.width(),
1165                                                                shape.indent)));
1166         if !attr_str.is_empty() {
1167             attr_str.push('\n');
1168             attr_str.push_str(&shape.indent.to_string(context.config));
1169         }
1170
1171         let type_annotation_spacing = type_annotation_spacing(context.config);
1172         let result = match name {
1173             Some(name) => {
1174                 format!("{}{}{}{}:{}",
1175                         attr_str,
1176                         vis,
1177                         name,
1178                         type_annotation_spacing.0,
1179                         type_annotation_spacing.1)
1180             }
1181             None => format!("{}{}", attr_str, vis),
1182         };
1183
1184         let last_line_width = last_line_width(&result);
1185         let budget = try_opt!(shape.width.checked_sub(last_line_width));
1186         let rewrite = try_opt!(self.ty.rewrite(context,
1187                                                Shape::legacy(budget,
1188                                                              shape.indent + last_line_width)));
1189         Some(result + &rewrite)
1190     }
1191 }
1192
1193 pub fn rewrite_static(prefix: &str,
1194                       vis: &ast::Visibility,
1195                       ident: ast::Ident,
1196                       ty: &ast::Ty,
1197                       mutability: ast::Mutability,
1198                       expr_opt: Option<&ptr::P<ast::Expr>>,
1199                       offset: Indent,
1200                       context: &RewriteContext)
1201                       -> Option<String> {
1202     let type_annotation_spacing = type_annotation_spacing(context.config);
1203     let prefix = format!("{}{} {}{}{}:{}",
1204                          format_visibility(vis),
1205                          prefix,
1206                          format_mutability(mutability),
1207                          ident,
1208                          type_annotation_spacing.0,
1209                          type_annotation_spacing.1);
1210     // 2 = " =".len()
1211     let ty_str = try_opt!(ty.rewrite(context,
1212                                      Shape::legacy(context.config.max_width - offset.block_indent -
1213                                                    prefix.len() -
1214                                                    2,
1215                                                    offset.block_only())));
1216
1217     if let Some(expr) = expr_opt {
1218         let lhs = format!("{}{} =", prefix, ty_str);
1219         // 1 = ;
1220         let remaining_width = context.config.max_width - offset.block_indent - 1;
1221         rewrite_assign_rhs(context,
1222                            lhs,
1223                            expr,
1224                            Shape::legacy(remaining_width, offset.block_only()))
1225                 .map(|s| s + ";")
1226     } else {
1227         let lhs = format!("{}{};", prefix, ty_str);
1228         Some(lhs)
1229     }
1230 }
1231
1232 pub fn rewrite_associated_type(ident: ast::Ident,
1233                                ty_opt: Option<&ptr::P<ast::Ty>>,
1234                                ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1235                                context: &RewriteContext,
1236                                indent: Indent)
1237                                -> Option<String> {
1238     let prefix = format!("type {}", ident);
1239
1240     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1241         let bounds: &[_] = ty_param_bounds;
1242         let bound_str = try_opt!(bounds.iter()
1243             .map(|ty_bound| {
1244                 ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent))
1245             })
1246             .intersperse(Some(" + ".to_string()))
1247             .collect::<Option<String>>());
1248         if bounds.len() > 0 {
1249             format!(": {}", bound_str)
1250         } else {
1251             String::new()
1252         }
1253     } else {
1254         String::new()
1255     };
1256
1257     if let Some(ty) = ty_opt {
1258         let ty_str = try_opt!(ty.rewrite(context,
1259                                          Shape::legacy(context.config.max_width -
1260                                                        indent.block_indent -
1261                                                        prefix.len() -
1262                                                        2,
1263                                                        indent.block_only())));
1264         Some(format!("{} = {};", prefix, ty_str))
1265     } else {
1266         Some(format!("{}{};", prefix, type_bounds_str))
1267     }
1268 }
1269
1270 pub fn rewrite_associated_impl_type(ident: ast::Ident,
1271                                     defaultness: ast::Defaultness,
1272                                     ty_opt: Option<&ptr::P<ast::Ty>>,
1273                                     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1274                                     context: &RewriteContext,
1275                                     indent: Indent)
1276                                     -> Option<String> {
1277     let result =
1278         try_opt!(rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent));
1279
1280     match defaultness {
1281         ast::Defaultness::Default => Some(format!("default {}", result)),
1282         _ => Some(result),
1283     }
1284 }
1285
1286 impl Rewrite for ast::FunctionRetTy {
1287     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1288         match *self {
1289             ast::FunctionRetTy::Default(_) => Some(String::new()),
1290             ast::FunctionRetTy::Ty(ref ty) => {
1291                 let inner_width = try_opt!(shape.width.checked_sub(3));
1292                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1293                     .map(|r| format!("-> {}", r))
1294             }
1295         }
1296     }
1297 }
1298
1299 impl Rewrite for ast::Arg {
1300     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1301         if is_named_arg(self) {
1302             let mut result = try_opt!(self.pat
1303                                           .rewrite(context,
1304                                                    Shape::legacy(shape.width, shape.indent)));
1305
1306             if self.ty.node != ast::TyKind::Infer {
1307                 if context.config.space_before_type_annotation {
1308                     result.push_str(" ");
1309                 }
1310                 result.push_str(":");
1311                 if context.config.space_after_type_annotation_colon {
1312                     result.push_str(" ");
1313                 }
1314                 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1315                 let ty_str = try_opt!(self.ty.rewrite(context,
1316                                                       Shape::legacy(max_width,
1317                                                                     shape.indent + result.len())));
1318                 result.push_str(&ty_str);
1319             }
1320
1321             Some(result)
1322         } else {
1323             self.ty.rewrite(context, shape)
1324         }
1325     }
1326 }
1327
1328 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1329                          args: &[ast::Arg],
1330                          context: &RewriteContext)
1331                          -> Option<String> {
1332     match explicit_self.node {
1333         ast::SelfKind::Region(lt, m) => {
1334             let mut_str = format_mutability(m);
1335             match lt {
1336                 Some(ref l) => {
1337                     let lifetime_str = try_opt!(l.rewrite(context,
1338                                                           Shape::legacy(usize::max_value(),
1339                                                                         Indent::empty())));
1340                     Some(format!("&{} {}self", lifetime_str, mut_str))
1341                 }
1342                 None => Some(format!("&{}self", mut_str)),
1343             }
1344         }
1345         ast::SelfKind::Explicit(ref ty, _) => {
1346             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1347
1348             let mutability = explicit_self_mutability(&args[0]);
1349             let type_str = try_opt!(ty.rewrite(context,
1350                                                Shape::legacy(usize::max_value(), Indent::empty())));
1351
1352             Some(format!("{}self: {}", format_mutability(mutability), type_str))
1353         }
1354         ast::SelfKind::Value(_) => {
1355             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1356
1357             let mutability = explicit_self_mutability(&args[0]);
1358
1359             Some(format!("{}self", format_mutability(mutability)))
1360         }
1361     }
1362 }
1363
1364 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1365 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1366 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1367     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1368         mutability
1369     } else {
1370         unreachable!()
1371     }
1372 }
1373
1374 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1375     if is_named_arg(arg) {
1376         arg.pat.span.lo
1377     } else {
1378         arg.ty.span.lo
1379     }
1380 }
1381
1382 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1383     match arg.ty.node {
1384         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1385         _ => arg.ty.span.hi,
1386     }
1387 }
1388
1389 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1390     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1391         ident.node != symbol::keywords::Invalid.ident()
1392     } else {
1393         true
1394     }
1395 }
1396
1397 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1398     match *ret {
1399         ast::FunctionRetTy::Default(ref span) => span.clone(),
1400         ast::FunctionRetTy::Ty(ref ty) => ty.span,
1401     }
1402 }
1403
1404 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1405     // Note that ty.span is the span for ty.ident, not the whole item.
1406     let lo = ty.span.lo;
1407     if let Some(ref def) = ty.default {
1408         return mk_sp(lo, def.span.hi);
1409     }
1410     if ty.bounds.is_empty() {
1411         return ty.span;
1412     }
1413     let hi = match ty.bounds[ty.bounds.len() - 1] {
1414         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1415         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1416     };
1417     mk_sp(lo, hi)
1418 }
1419
1420 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1421     match *pred {
1422         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1423         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1424         ast::WherePredicate::EqPredicate(ref p) => p.span,
1425     }
1426 }
1427
1428 // Return type is (result, force_new_line_for_brace)
1429 fn rewrite_fn_base(context: &RewriteContext,
1430                    indent: Indent,
1431                    ident: ast::Ident,
1432                    fd: &ast::FnDecl,
1433                    generics: &ast::Generics,
1434                    unsafety: ast::Unsafety,
1435                    constness: ast::Constness,
1436                    defaultness: ast::Defaultness,
1437                    abi: abi::Abi,
1438                    vis: &ast::Visibility,
1439                    span: Span,
1440                    newline_brace: bool,
1441                    has_body: bool)
1442                    -> Option<(String, bool)> {
1443     let mut force_new_line_for_brace = false;
1444
1445     let where_clause = &generics.where_clause;
1446
1447     let mut result = String::with_capacity(1024);
1448     // Vis unsafety abi.
1449     result.push_str(&*format_visibility(vis));
1450
1451     if let ast::Defaultness::Default = defaultness {
1452         result.push_str("default ");
1453     }
1454
1455     if let ast::Constness::Const = constness {
1456         result.push_str("const ");
1457     }
1458
1459     result.push_str(::utils::format_unsafety(unsafety));
1460
1461     if abi != abi::Abi::Rust {
1462         result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1463     }
1464
1465     // fn foo
1466     result.push_str("fn ");
1467     result.push_str(&ident.to_string());
1468
1469     // Generics.
1470     let generics_indent = indent + result.len();
1471     let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1472     let generics_str = try_opt!(rewrite_generics(context,
1473                                                  generics,
1474                                                  Shape::legacy(context.config.max_width, indent),
1475                                                  generics_indent,
1476                                                  generics_span));
1477     result.push_str(&generics_str);
1478
1479     // Note that if the width and indent really matter, we'll re-layout the
1480     // return type later anyway.
1481     let ret_str = try_opt!(fd.output
1482                                .rewrite(&context,
1483                                         Shape::legacy(context.config.max_width -
1484                                                       indent.width(),
1485                                                       indent)));
1486
1487     let multi_line_ret_str = ret_str.contains('\n');
1488     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1489
1490     // Args.
1491     let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1492         try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1493
1494     if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1495        context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1496         arg_indent = indent.block_indent(context.config);
1497         multi_line_budget = context.config.max_width - arg_indent.width();
1498     }
1499
1500     debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1501            one_line_budget,
1502            multi_line_budget,
1503            arg_indent);
1504
1505     // Check if vertical layout was forced.
1506     if one_line_budget == 0 {
1507         if context.config.fn_args_paren_newline {
1508             result.push('\n');
1509             result.push_str(&arg_indent.to_string(context.config));
1510             arg_indent = arg_indent + 1; // extra space for `(`
1511             result.push('(');
1512             if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1513                 result.push(' ')
1514             }
1515         } else {
1516             result.push_str("(\n");
1517             result.push_str(&arg_indent.to_string(context.config));
1518         }
1519     } else {
1520         result.push('(');
1521         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1522             result.push(' ')
1523         }
1524     }
1525
1526     if multi_line_ret_str {
1527         one_line_budget = 0;
1528     }
1529
1530     // A conservative estimation, to goal is to be over all parens in generics
1531     let args_start = generics.ty_params
1532         .last()
1533         .map_or(span.lo, |tp| end_typaram(tp));
1534     let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1535                           span_for_return(&fd.output).lo);
1536     let arg_str = try_opt!(rewrite_args(context,
1537                                         &fd.inputs,
1538                                         fd.get_self().as_ref(),
1539                                         one_line_budget,
1540                                         multi_line_budget,
1541                                         indent,
1542                                         arg_indent,
1543                                         args_span,
1544                                         fd.variadic));
1545
1546     let multi_line_arg_str = arg_str.contains('\n');
1547
1548     let put_args_in_block = match context.config.fn_args_layout {
1549         FnArgLayoutStyle::Block => multi_line_arg_str,
1550         FnArgLayoutStyle::BlockAlways => true,
1551         _ => false,
1552     } && !fd.inputs.is_empty();
1553
1554     if put_args_in_block {
1555         arg_indent = indent.block_indent(context.config);
1556         result.push('\n');
1557         result.push_str(&arg_indent.to_string(context.config));
1558         result.push_str(&arg_str);
1559         result.push('\n');
1560         result.push_str(&indent.to_string(context.config));
1561         result.push(')');
1562     } else {
1563         result.push_str(&arg_str);
1564         if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1565             result.push(' ')
1566         }
1567         result.push(')');
1568     }
1569
1570     // Return type.
1571     if !ret_str.is_empty() {
1572         let ret_should_indent = match context.config.fn_args_layout {
1573             // If our args are block layout then we surely must have space.
1574             FnArgLayoutStyle::Block if put_args_in_block => false,
1575             FnArgLayoutStyle::BlockAlways => false,
1576             _ => {
1577                 // If we've already gone multi-line, or the return type would push over the max
1578                 // width, then put the return type on a new line. With the +1 for the signature
1579                 // length an additional space between the closing parenthesis of the argument and
1580                 // the arrow '->' is considered.
1581                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1582
1583                 // If there is no where clause, take into account the space after the return type
1584                 // and the brace.
1585                 if where_clause.predicates.is_empty() {
1586                     sig_length += 2;
1587                 }
1588
1589                 let overlong_sig = sig_length > context.config.max_width;
1590
1591                 result.contains('\n') || multi_line_ret_str || overlong_sig
1592             }
1593         };
1594         let ret_indent = if ret_should_indent {
1595             let indent = match context.config.fn_return_indent {
1596                 ReturnIndent::WithWhereClause => indent + 4,
1597                 // Aligning with non-existent args looks silly.
1598                 _ if arg_str.is_empty() => {
1599                     force_new_line_for_brace = true;
1600                     indent + 4
1601                 }
1602                 // FIXME: we might want to check that using the arg indent
1603                 // doesn't blow our budget, and if it does, then fallback to
1604                 // the where clause indent.
1605                 _ => arg_indent,
1606             };
1607
1608             result.push('\n');
1609             result.push_str(&indent.to_string(context.config));
1610             indent
1611         } else {
1612             result.push(' ');
1613             Indent::new(indent.width(), result.len())
1614         };
1615
1616         if multi_line_ret_str {
1617             // Now that we know the proper indent and width, we need to
1618             // re-layout the return type.
1619             let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1620             let ret_str = try_opt!(fd.output.rewrite(context, Shape::legacy(budget, ret_indent)));
1621             result.push_str(&ret_str);
1622         } else {
1623             result.push_str(&ret_str);
1624         }
1625
1626         // Comment between return type and the end of the decl.
1627         let snippet_lo = fd.output.span().hi;
1628         if where_clause.predicates.is_empty() {
1629             let snippet_hi = span.hi;
1630             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1631             let snippet = snippet.trim();
1632             if !snippet.is_empty() {
1633                 result.push(' ');
1634                 result.push_str(snippet);
1635             }
1636         } else {
1637             // FIXME it would be nice to catch comments between the return type
1638             // and the where clause, but we don't have a span for the where
1639             // clause.
1640         }
1641     }
1642
1643     let should_compress_where = match context.config.where_density {
1644         Density::Compressed => !result.contains('\n') || put_args_in_block,
1645         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1646         _ => false,
1647     } || (put_args_in_block && ret_str.is_empty());
1648
1649     let where_density = if should_compress_where {
1650         Density::Compressed
1651     } else {
1652         Density::Tall
1653     };
1654
1655     // Where clause.
1656     let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1657     let where_clause_str = try_opt!(rewrite_where_clause(context,
1658                                                          where_clause,
1659                                                          context.config,
1660                                                          context.config.fn_brace_style,
1661                                                          Shape::legacy(where_budget, indent),
1662                                                          where_density,
1663                                                          "{",
1664                                                          has_body,
1665                                                          Some(span.hi)));
1666
1667     if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1668        !where_clause_str.contains('\n') {
1669         result.push('\n');
1670     }
1671
1672     result.push_str(&where_clause_str);
1673
1674     Some((result, force_new_line_for_brace))
1675 }
1676
1677 fn rewrite_args(context: &RewriteContext,
1678                 args: &[ast::Arg],
1679                 explicit_self: Option<&ast::ExplicitSelf>,
1680                 one_line_budget: usize,
1681                 multi_line_budget: usize,
1682                 indent: Indent,
1683                 arg_indent: Indent,
1684                 span: Span,
1685                 variadic: bool)
1686                 -> Option<String> {
1687     let mut arg_item_strs =
1688         try_opt!(args.iter()
1689                      .map(|arg| {
1690                               arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
1691                           })
1692                      .collect::<Option<Vec<_>>>());
1693
1694     // Account for sugary self.
1695     // FIXME: the comment for the self argument is dropped. This is blocked
1696     // on rust issue #27522.
1697     let min_args =
1698         explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1699             .map_or(1, |self_str| {
1700                 arg_item_strs[0] = self_str;
1701                 2
1702             });
1703
1704     // Comments between args.
1705     let mut arg_items = Vec::new();
1706     if min_args == 2 {
1707         arg_items.push(ListItem::from_str(""));
1708     }
1709
1710     // FIXME(#21): if there are no args, there might still be a comment, but
1711     // without spans for the comment or parens, there is no chance of
1712     // getting it right. You also don't get to put a comment on self, unless
1713     // it is explicit.
1714     if args.len() >= min_args || variadic {
1715         let comment_span_start = if min_args == 2 {
1716             let second_arg_start = if arg_has_pattern(&args[1]) {
1717                 args[1].pat.span.lo
1718             } else {
1719                 args[1].ty.span.lo
1720             };
1721             let reduced_span = mk_sp(span.lo, second_arg_start);
1722
1723             context.codemap.span_after_last(reduced_span, ",")
1724         } else {
1725             span.lo
1726         };
1727
1728         enum ArgumentKind<'a> {
1729             Regular(&'a ast::Arg),
1730             Variadic(BytePos),
1731         }
1732
1733         let variadic_arg = if variadic {
1734             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1735             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1736             Some(ArgumentKind::Variadic(variadic_start))
1737         } else {
1738             None
1739         };
1740
1741         let more_items = itemize_list(context.codemap,
1742                                       args[min_args - 1..]
1743                                           .iter()
1744                                           .map(ArgumentKind::Regular)
1745                                           .chain(variadic_arg),
1746                                       ")",
1747                                       |arg| match *arg {
1748                                           ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1749                                           ArgumentKind::Variadic(start) => start,
1750                                       },
1751                                       |arg| match *arg {
1752                                           ArgumentKind::Regular(arg) => arg.ty.span.hi,
1753                                           ArgumentKind::Variadic(start) => start + BytePos(3),
1754                                       },
1755                                       |arg| match *arg {
1756                                           ArgumentKind::Regular(..) => None,
1757                                           ArgumentKind::Variadic(..) => Some("...".to_owned()),
1758                                       },
1759                                       comment_span_start,
1760                                       span.hi);
1761
1762         arg_items.extend(more_items);
1763     }
1764
1765     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1766         item.item = Some(arg);
1767     }
1768
1769     let indent = match context.config.fn_arg_indent {
1770         BlockIndentStyle::Inherit => indent,
1771         BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1772         BlockIndentStyle::Visual => arg_indent,
1773     };
1774
1775     let tactic = definitive_tactic(&arg_items,
1776                                    context.config.fn_args_density.to_list_tactic(),
1777                                    one_line_budget);
1778     let budget = match tactic {
1779         DefinitiveListTactic::Horizontal => one_line_budget,
1780         _ => multi_line_budget,
1781     };
1782
1783     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1784
1785     let end_with_newline = match context.config.fn_args_layout {
1786         FnArgLayoutStyle::Block |
1787         FnArgLayoutStyle::BlockAlways => true,
1788         _ => false,
1789     };
1790
1791     let fmt = ListFormatting {
1792         tactic: tactic,
1793         separator: ",",
1794         trailing_separator: SeparatorTactic::Never,
1795         shape: Shape::legacy(budget, indent),
1796         ends_with_newline: end_with_newline,
1797         config: context.config,
1798     };
1799
1800     write_list(&arg_items, &fmt)
1801 }
1802
1803 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1804     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1805         ident.node != symbol::keywords::Invalid.ident()
1806     } else {
1807         true
1808     }
1809 }
1810
1811 fn compute_budgets_for_args(context: &RewriteContext,
1812                             result: &str,
1813                             indent: Indent,
1814                             ret_str_len: usize,
1815                             newline_brace: bool)
1816                             -> Option<((usize, usize, Indent))> {
1817     debug!("compute_budgets_for_args {} {:?}, {}, {}",
1818            result.len(),
1819            indent,
1820            ret_str_len,
1821            newline_brace);
1822     // Try keeping everything on the same line.
1823     if !result.contains('\n') {
1824         // 3 = `() `, space is before ret_string.
1825         let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1826         if !newline_brace {
1827             used_space += 2;
1828         }
1829         let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1830
1831         if one_line_budget > 0 {
1832             // 4 = "() {".len()
1833             let multi_line_budget =
1834                 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1835
1836             return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1837         }
1838     }
1839
1840     // Didn't work. we must force vertical layout and put args on a newline.
1841     let new_indent = indent.block_indent(context.config);
1842     let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1843     let max_space = context.config.max_width;
1844     if used_space <= max_space {
1845         Some((0, max_space - used_space, new_indent))
1846     } else {
1847         // Whoops! bankrupt.
1848         None
1849     }
1850 }
1851
1852 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1853     match config.fn_brace_style {
1854         BraceStyle::AlwaysNextLine => true,
1855         BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1856         _ => false,
1857     }
1858 }
1859
1860 fn rewrite_generics(context: &RewriteContext,
1861                     generics: &ast::Generics,
1862                     shape: Shape,
1863                     // TODO shouldn't need this
1864                     generics_offset: Indent,
1865                     span: Span)
1866                     -> Option<String> {
1867     // FIXME: convert bounds to where clauses where they get too big or if
1868     // there is a where clause at all.
1869     let lifetimes: &[_] = &generics.lifetimes;
1870     let tys: &[_] = &generics.ty_params;
1871     if lifetimes.is_empty() && tys.is_empty() {
1872         return Some(String::new());
1873     }
1874
1875     let offset = match context.config.generics_indent {
1876         BlockIndentStyle::Inherit => shape.indent,
1877         BlockIndentStyle::Tabbed => shape.indent.block_indent(context.config),
1878         // 1 = <
1879         BlockIndentStyle::Visual => generics_offset + 1,
1880     };
1881
1882     let h_budget = try_opt!(shape.width.checked_sub(generics_offset.width() + 2));
1883     // FIXME: might need to insert a newline if the generics are really long.
1884
1885     // Strings for the generics.
1886     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1887     let ty_strs = tys.iter()
1888         .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
1889
1890     // Extract comments between generics.
1891     let lt_spans = lifetimes.iter().map(|l| {
1892         let hi = if l.bounds.is_empty() {
1893             l.lifetime.span.hi
1894         } else {
1895             l.bounds[l.bounds.len() - 1].span.hi
1896         };
1897         mk_sp(l.lifetime.span.lo, hi)
1898     });
1899     let ty_spans = tys.iter().map(span_for_ty_param);
1900
1901     let items = itemize_list(context.codemap,
1902                              lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1903                              ">",
1904                              |&(sp, _)| sp.lo,
1905                              |&(sp, _)| sp.hi,
1906                              // FIXME: don't clone
1907                              |&(_, ref str)| str.clone(),
1908                              context.codemap.span_after(span, "<"),
1909                              span.hi);
1910     let list_str =
1911         try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
1912
1913     Some(if context.config.spaces_within_angle_brackets {
1914              format!("< {} >", list_str)
1915          } else {
1916              format!("<{}>", list_str)
1917          })
1918 }
1919
1920 fn rewrite_trait_bounds(context: &RewriteContext,
1921                         type_param_bounds: &ast::TyParamBounds,
1922                         shape: Shape)
1923                         -> Option<String> {
1924     let bounds: &[_] = type_param_bounds;
1925
1926     if bounds.is_empty() {
1927         return Some(String::new());
1928     }
1929
1930     let bound_str = try_opt!(bounds.iter()
1931                                  .map(|ty_bound| ty_bound.rewrite(&context, shape))
1932                                  .intersperse(Some(" + ".to_string()))
1933                                  .collect::<Option<String>>());
1934
1935     let mut result = String::new();
1936     result.push_str(": ");
1937     result.push_str(&bound_str);
1938     Some(result)
1939 }
1940
1941 fn rewrite_where_clause(context: &RewriteContext,
1942                         where_clause: &ast::WhereClause,
1943                         config: &Config,
1944                         brace_style: BraceStyle,
1945                         shape: Shape,
1946                         density: Density,
1947                         terminator: &str,
1948                         allow_trailing_comma: bool,
1949                         span_end: Option<BytePos>)
1950                         -> Option<String> {
1951     if where_clause.predicates.is_empty() {
1952         return Some(String::new());
1953     }
1954
1955     let extra_indent = match context.config.where_indent {
1956         BlockIndentStyle::Inherit => Indent::empty(),
1957         BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1958     };
1959
1960     let offset = match context.config.where_pred_indent {
1961         BlockIndentStyle::Inherit => shape.indent + extra_indent,
1962         BlockIndentStyle::Tabbed => shape.indent + extra_indent.block_indent(config),
1963         // 6 = "where ".len()
1964         BlockIndentStyle::Visual => shape.indent + extra_indent + 6,
1965     };
1966     // FIXME: if where_pred_indent != Visual, then the budgets below might
1967     // be out by a char or two.
1968
1969     let budget = context.config.max_width - offset.width();
1970     let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1971     // If we don't have the start of the next span, then use the end of the
1972     // predicates, but that means we miss comments.
1973     let len = where_clause.predicates.len();
1974     let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1975     let span_end = span_end.unwrap_or(end_of_preds);
1976     let items = itemize_list(context.codemap,
1977                              where_clause.predicates.iter(),
1978                              terminator,
1979                              |pred| span_for_where_pred(pred).lo,
1980                              |pred| span_for_where_pred(pred).hi,
1981                              |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
1982                              span_start,
1983                              span_end);
1984     let item_vec = items.collect::<Vec<_>>();
1985     // FIXME: we don't need to collect here if the where_layout isn't
1986     // HorizontalVertical.
1987     let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1988     let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1989
1990     let fmt = ListFormatting {
1991         tactic: tactic,
1992         separator: ",",
1993         trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1994         shape: Shape::legacy(budget, offset),
1995         ends_with_newline: true,
1996         config: context.config,
1997     };
1998     let preds_str = try_opt!(write_list(&item_vec, &fmt));
1999
2000     let end_length = if terminator == "{" {
2001         // If the brace is on the next line we don't need to count it otherwise it needs two
2002         // characters " {"
2003         match brace_style {
2004             BraceStyle::AlwaysNextLine |
2005             BraceStyle::SameLineWhere => 0,
2006             BraceStyle::PreferSameLine => 2,
2007         }
2008     } else if terminator == "=" {
2009         2
2010     } else {
2011         terminator.len()
2012     };
2013     if density == Density::Tall || preds_str.contains('\n') ||
2014        shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
2015         Some(format!("\n{}where {}",
2016                      (shape.indent + extra_indent).to_string(context.config),
2017                      preds_str))
2018     } else {
2019         Some(format!(" where {}", preds_str))
2020     }
2021 }
2022
2023 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2024     format!("{}{}{}", format_visibility(vis), item_name, ident)
2025 }
2026
2027 fn format_generics(context: &RewriteContext,
2028                    generics: &ast::Generics,
2029                    opener: &str,
2030                    terminator: &str,
2031                    brace_style: BraceStyle,
2032                    force_same_line_brace: bool,
2033                    offset: Indent,
2034                    generics_offset: Indent,
2035                    span: Span)
2036                    -> Option<String> {
2037     let mut result = try_opt!(rewrite_generics(context,
2038                                                generics,
2039                                                Shape::legacy(context.config.max_width, offset),
2040                                                generics_offset,
2041                                                span));
2042
2043     if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2044         let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
2045         let where_clause_str = try_opt!(rewrite_where_clause(context,
2046                                                              &generics.where_clause,
2047                                                              context.config,
2048                                                              brace_style,
2049                                                              Shape::legacy(budget,
2050                                                                            offset.block_only()),
2051                                                              Density::Tall,
2052                                                              terminator,
2053                                                              true,
2054                                                              Some(span.hi)));
2055         result.push_str(&where_clause_str);
2056         if !force_same_line_brace &&
2057            (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2058             result.push('\n');
2059             result.push_str(&offset.block_only().to_string(context.config));
2060         } else {
2061             result.push(' ');
2062         }
2063         result.push_str(opener);
2064     } else {
2065         if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
2066             result.push('\n');
2067             result.push_str(&offset.block_only().to_string(context.config));
2068         } else {
2069             result.push(' ');
2070         }
2071         result.push_str(opener);
2072     }
2073
2074     Some(result)
2075 }