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