]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Format comments in struct literals
[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 {ReturnIndent, BraceStyle};
14 use utils::{format_visibility, make_indent, contains_skip, span_after};
15 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
16 use comment::FindUncommented;
17 use visitor::FmtVisitor;
18
19 use syntax::{ast, abi};
20 use syntax::codemap::{self, Span, BytePos};
21 use syntax::print::pprust;
22 use syntax::parse::token;
23
24 impl<'a> FmtVisitor<'a> {
25     pub fn rewrite_fn(&mut self,
26                       indent: usize,
27                       ident: ast::Ident,
28                       fd: &ast::FnDecl,
29                       explicit_self: Option<&ast::ExplicitSelf>,
30                       generics: &ast::Generics,
31                       unsafety: &ast::Unsafety,
32                       constness: &ast::Constness,
33                       abi: &abi::Abi,
34                       vis: ast::Visibility,
35                       span: Span)
36         -> String
37     {
38         let newline_brace = self.newline_for_brace(&generics.where_clause);
39
40         let mut result = self.rewrite_fn_base(indent,
41                                               ident,
42                                               fd,
43                                               explicit_self,
44                                               generics,
45                                               unsafety,
46                                               constness,
47                                               abi,
48                                               vis,
49                                               span,
50                                               newline_brace);
51
52         // Prepare for the function body by possibly adding a newline and indent.
53         // FIXME we'll miss anything between the end of the signature and the start
54         // of the body, but we need more spans from the compiler to solve this.
55         if newline_brace {
56             result.push('\n');
57             result.push_str(&make_indent(indent));
58         } else {
59             result.push(' ');
60         }
61
62         result
63     }
64
65     pub fn rewrite_required_fn(&mut self,
66                                indent: usize,
67                                ident: ast::Ident,
68                                sig: &ast::MethodSig,
69                                span: Span)
70         -> String
71     {
72         // Drop semicolon or it will be interpreted as comment
73         let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
74
75         let mut result = self.rewrite_fn_base(indent,
76                                               ident,
77                                               &sig.decl,
78                                               Some(&sig.explicit_self),
79                                               &sig.generics,
80                                               &sig.unsafety,
81                                               &sig.constness,
82                                               &sig.abi,
83                                               ast::Visibility::Inherited,
84                                               span,
85                                               false);
86
87         // Re-attach semicolon
88         result.push(';');
89
90         result
91     }
92
93     fn rewrite_fn_base(&mut self,
94                        indent: usize,
95                        ident: ast::Ident,
96                        fd: &ast::FnDecl,
97                        explicit_self: Option<&ast::ExplicitSelf>,
98                        generics: &ast::Generics,
99                        unsafety: &ast::Unsafety,
100                        constness: &ast::Constness,
101                        abi: &abi::Abi,
102                        vis: ast::Visibility,
103                        span: Span,
104                        newline_brace: bool)
105         -> String
106     {
107         // FIXME we'll lose any comments in between parts of the function decl, but anyone
108         // who comments there probably deserves what they get.
109
110         let where_clause = &generics.where_clause;
111
112         let mut result = String::with_capacity(1024);
113         // Vis unsafety abi.
114         result.push_str(format_visibility(vis));
115
116         if let &ast::Unsafety::Unsafe = unsafety {
117             result.push_str("unsafe ");
118         }
119         if let &ast::Constness::Const = constness {
120             result.push_str("const ");
121         }
122         if *abi != abi::Rust {
123             result.push_str("extern ");
124             result.push_str(&abi.to_string());
125             result.push(' ');
126         }
127
128         // fn foo
129         result.push_str("fn ");
130         result.push_str(&token::get_ident(ident));
131
132         // Generics.
133         let generics_indent = indent + result.len();
134         result.push_str(&self.rewrite_generics(generics,
135                                                generics_indent,
136                                                codemap::mk_sp(span.lo,
137                                                               span_for_return(&fd.output).lo)));
138
139         let ret_str = self.rewrite_return(&fd.output);
140
141         // Args.
142         let (one_line_budget, multi_line_budget, mut arg_indent) =
143             self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
144
145         debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
146                one_line_budget, multi_line_budget, arg_indent);
147
148         // Check if vertical layout was forced by compute_budget_for_args.
149         if one_line_budget <= 0 {
150             if self.config.fn_args_paren_newline {
151                 result.push('\n');
152                 result.push_str(&make_indent(arg_indent));
153                 arg_indent = arg_indent + 1; // extra space for `(`
154                 result.push('(');
155             } else {
156                 result.push_str("(\n");
157                 result.push_str(&make_indent(arg_indent));
158             }
159         } else {
160             result.push('(');
161         }
162
163         result.push_str(&self.rewrite_args(&fd.inputs,
164                                            explicit_self,
165                                            one_line_budget,
166                                            multi_line_budget,
167                                            arg_indent,
168                                            codemap::mk_sp(span_after(span, "(", self.codemap),
169                                                           span_for_return(&fd.output).lo)));
170         result.push(')');
171
172         // Return type.
173         if ret_str.len() > 0 {
174             // If we've already gone multi-line, or the return type would push
175             // over the max width, then put the return type on a new line.
176             if result.contains("\n") ||
177                result.len() + indent + ret_str.len() > self.config.max_width {
178                 let indent = match self.config.fn_return_indent {
179                     ReturnIndent::WithWhereClause => indent + 4,
180                     // TODO we might want to check that using the arg indent doesn't
181                     // blow our budget, and if it does, then fallback to the where
182                     // clause indent.
183                     _ => arg_indent,
184                 };
185
186                 result.push('\n');
187                 result.push_str(&make_indent(indent));
188             } else {
189                 result.push(' ');
190             }
191             result.push_str(&ret_str);
192
193             // Comment between return type and the end of the decl.
194             let snippet_lo = fd.output.span().hi;
195             if where_clause.predicates.len() == 0 {
196                 let snippet_hi = span.hi;
197                 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
198                 let snippet = snippet.trim();
199                 if snippet.len() > 0 {
200                     result.push(' ');
201                     result.push_str(snippet);
202                 }
203             } else {
204                 // FIXME it would be nice to catch comments between the return type
205                 // and the where clause, but we don't have a span for the where
206                 // clause.
207             }
208         }
209
210         // Where clause.
211         result.push_str(&self.rewrite_where_clause(where_clause,
212                                                    indent,
213                                                    span.hi));
214
215         result
216     }
217
218     fn rewrite_args(&self,
219                     args: &[ast::Arg],
220                     explicit_self: Option<&ast::ExplicitSelf>,
221                     one_line_budget: usize,
222                     multi_line_budget: usize,
223                     arg_indent: usize,
224                     span: Span)
225         -> String
226     {
227         let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
228         // Account for sugary self.
229         let mut min_args = 1;
230         if let Some(explicit_self) = explicit_self {
231             match explicit_self.node {
232                 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
233                     let lt_str = match lt {
234                         &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
235                         &None => String::new(),
236                     };
237                     let mut_str = match m {
238                         &ast::Mutability::MutMutable => "mut ".to_owned(),
239                         &ast::Mutability::MutImmutable => String::new(),
240                     };
241                     arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
242                     min_args = 2;
243                 }
244                 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
245                     arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
246                 }
247                 ast::ExplicitSelf_::SelfValue(_) => {
248                     assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
249
250                     // this hacky solution caused by absence of `Mutability` in `SelfValue`.
251                     let mut_str = {
252                         if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
253                                 = args[0].pat.node {
254                             match mutability {
255                                 ast::Mutability::MutMutable => "mut ",
256                                 ast::Mutability::MutImmutable => "",
257                             }
258                         } else {
259                             panic!("there is a bug or change in structure of AST, aborting.");
260                         }
261                     };
262
263                     arg_item_strs[0] = format!("{}self", mut_str);
264                     min_args = 2;
265                 }
266                 _ => {}
267             }
268         }
269
270         // Comments between args
271         let mut arg_items = Vec::new();
272         if min_args == 2 {
273             arg_items.push(ListItem::from_str(""));
274         }
275
276         // TODO if there are no args, there might still be a comment, but without
277         // spans for the comment or parens, there is no chance of getting it right.
278         // You also don't get to put a comment on self, unless it is explicit.
279         if args.len() >= min_args {
280             let comment_span_start = if min_args == 2 {
281                 span_after(span, ",", self.codemap)
282             } else {
283                 span.lo
284             };
285
286             arg_items = itemize_list(self.codemap,
287                                      arg_items,
288                                      args[min_args-1..].iter(),
289                                      ",",
290                                      ")",
291                                      |arg| arg.pat.span.lo,
292                                      |arg| arg.ty.span.hi,
293                                      |_| String::new(),
294                                      comment_span_start,
295                                      span.hi);
296         }
297
298         assert_eq!(arg_item_strs.len(), arg_items.len());
299
300         for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
301             item.item = arg;
302         }
303
304         let fmt = ListFormatting {
305             tactic: ListTactic::HorizontalVertical,
306             separator: ",",
307             trailing_separator: SeparatorTactic::Never,
308             indent: arg_indent,
309             h_width: one_line_budget,
310             v_width: multi_line_budget,
311             is_expression: true,
312         };
313
314         write_list(&arg_items, &fmt)
315     }
316
317     fn compute_budgets_for_args(&self,
318                                 result: &str,
319                                 indent: usize,
320                                 ret_str_len: usize,
321                                 newline_brace: bool)
322         -> (usize, usize, usize)
323     {
324         let mut budgets = None;
325
326         // Try keeping everything on the same line
327         if !result.contains("\n") {
328             // 3 = `() `, space is before ret_string
329             let mut used_space = indent + result.len() + ret_str_len + 3;
330             if !newline_brace {
331                 used_space += 2;
332             }
333             let one_line_budget = if used_space > self.config.max_width {
334                 0
335             } else {
336                 self.config.max_width - used_space
337             };
338
339             // 2 = `()`
340             let used_space = indent + result.len() + 2;
341             let max_space = self.config.ideal_width + self.config.leeway;
342             debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
343                    used_space, max_space);
344             if used_space < max_space {
345                 budgets = Some((one_line_budget,
346                                 max_space - used_space,
347                                 indent + result.len() + 1));
348             }
349         }
350
351         // Didn't work. we must force vertical layout and put args on a newline.
352         if let None = budgets {
353             let new_indent = indent + self.config.tab_spaces;
354             let used_space = new_indent + 2; // account for `(` and `)`
355             let max_space = self.config.ideal_width + self.config.leeway;
356             if used_space > max_space {
357                 // Whoops! bankrupt.
358                 // TODO take evasive action, perhaps kill the indent or something.
359             } else {
360                 budgets = Some((0, max_space - used_space, new_indent));
361             }
362         }
363
364         budgets.unwrap()
365     }
366
367     fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
368         match self.config.fn_brace_style {
369             BraceStyle::AlwaysNextLine => true,
370             BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
371             _ => false,
372         }
373     }
374
375     pub fn visit_enum(&mut self,
376                       ident: ast::Ident,
377                       vis: ast::Visibility,
378                       enum_def: &ast::EnumDef,
379                       generics: &ast::Generics,
380                       span: Span)
381     {
382         let header_str = self.format_header("enum ", ident, vis);
383         self.changes.push_str_span(span, &header_str);
384
385         let enum_snippet = self.snippet(span);
386         let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
387         let generics_str = self.format_generics(generics,
388                                                 " {",
389                                                 self.block_indent + self.config.tab_spaces,
390                                                 codemap::mk_sp(span.lo,
391                                                                body_start));
392         self.changes.push_str_span(span, &generics_str);
393
394         self.last_pos = body_start;
395         self.block_indent += self.config.tab_spaces;
396         for (i, f) in enum_def.variants.iter().enumerate() {
397             let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
398                 span.hi
399             } else {
400                 enum_def.variants[i + 1].span.lo
401             };
402
403             self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
404         }
405         self.block_indent -= self.config.tab_spaces;
406
407         self.format_missing_with_indent(span.lo + BytePos(enum_snippet.rfind('}').unwrap() as u32));
408         self.changes.push_str_span(span, "}");
409     }
410
411     // Variant of an enum
412     fn visit_variant(&mut self,
413                      field: &ast::Variant,
414                      last_field: bool,
415                      next_span_start: BytePos)
416     {
417         if self.visit_attrs(&field.node.attrs) {
418             return;
419         }
420
421         self.format_missing_with_indent(field.span.lo);
422
423         match field.node.kind {
424             ast::VariantKind::TupleVariantKind(ref types) => {
425                 let vis = format_visibility(field.node.vis);
426                 self.changes.push_str_span(field.span, vis);
427                 let name = field.node.name.to_string();
428                 self.changes.push_str_span(field.span, &name);
429
430                 let mut result = String::new();
431
432                 if types.len() > 0 {
433                     let items = itemize_list(self.codemap,
434                                              Vec::new(),
435                                              types.iter(),
436                                              ",",
437                                              ")",
438                                              |arg| arg.ty.span.lo,
439                                              |arg| arg.ty.span.hi,
440                                              |arg| pprust::ty_to_string(&arg.ty),
441                                              span_after(field.span, "(", self.codemap),
442                                              next_span_start);
443
444                     result.push('(');
445
446                     let indent = self.block_indent
447                                  + vis.len()
448                                  + field.node.name.to_string().len()
449                                  + 1; // Open paren
450
451                     let comma_cost = if self.config.enum_trailing_comma { 1 } else { 0 };
452                     let budget = self.config.ideal_width - indent - comma_cost - 1; // 1 = )
453
454                     let fmt = ListFormatting {
455                         tactic: ListTactic::HorizontalVertical,
456                         separator: ",",
457                         trailing_separator: SeparatorTactic::Never,
458                         indent: indent,
459                         h_width: budget,
460                         v_width: budget,
461                         is_expression: false,
462                     };
463                     result.push_str(&write_list(&items, &fmt));
464                     result.push(')');
465                 }
466
467                 if let Some(ref expr) = field.node.disr_expr {
468                     result.push_str(" = ");
469                     let expr_snippet = self.snippet(expr.span);
470                     result.push_str(&expr_snippet);
471
472                     // Make sure we do not exceed column limit
473                     // 4 = " = ,"
474                     assert!(self.config.max_width >= vis.len() + name.len() + expr_snippet.len() + 4,
475                             "Enum variant exceeded column limit");
476                 }
477
478                 self.changes.push_str_span(field.span, &result);
479
480                 if !last_field || self.config.enum_trailing_comma {
481                     self.changes.push_str_span(field.span, ",");
482                 }
483             },
484             ast::VariantKind::StructVariantKind(ref struct_def) => {
485                 let result = self.format_struct("",
486                                                 field.node.name,
487                                                 field.node.vis,
488                                                 struct_def,
489                                                 None,
490                                                 field.span,
491                                                 self.block_indent);
492
493                 self.changes.push_str_span(field.span, &result)
494             }
495         }
496
497         self.last_pos = field.span.hi + BytePos(1);
498     }
499
500     fn format_struct(&self,
501                      item_name: &str,
502                      ident: ast::Ident,
503                      vis: ast::Visibility,
504                      struct_def: &ast::StructDef,
505                      generics: Option<&ast::Generics>,
506                      span: Span,
507                      offset: usize) -> String
508     {
509         let mut result = String::with_capacity(1024);
510
511         let header_str = self.format_header(item_name, ident, vis);
512         result.push_str(&header_str);
513
514         if struct_def.fields.len() == 0 {
515             result.push(';');
516             return result;
517         }
518
519         let is_tuple = match struct_def.fields[0].node.kind {
520             ast::StructFieldKind::NamedField(..) => false,
521             ast::StructFieldKind::UnnamedField(..) => true
522         };
523
524         let (opener, terminator) = if is_tuple { ("(", ")") } else { (" {", "}") };
525
526         let generics_str = match generics {
527             Some(g) => self.format_generics(g,
528                                             opener,
529                                             offset + header_str.len(),
530                                             codemap::mk_sp(span.lo,
531                                                            struct_def.fields[0].span.lo)),
532             None => opener.to_owned()
533         };
534         result.push_str(&generics_str);
535
536         let items = itemize_list(self.codemap,
537                                  Vec::new(),
538                                  struct_def.fields.iter(),
539                                  ",",
540                                  terminator,
541                                  |field| {
542                                       // Include attributes and doc comments,
543                                       // if present
544                                       if field.node.attrs.len() > 0 {
545                                           field.node.attrs[0].span.lo
546                                       } else {
547                                           field.span.lo
548                                       }
549                                  },
550                                  |field| field.node.ty.span.hi,
551                                  |field| self.format_field(field),
552                                  span_after(span, opener.trim(), self.codemap),
553                                  span.hi);
554
555         // 2 terminators and a semicolon
556         let used_budget = offset + header_str.len() + generics_str.len() + 3;
557
558         // Conservative approximation
559         let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
560         let break_line = !is_tuple ||
561                          generics_str.contains('\n') ||
562                          single_line_cost as usize + used_budget > self.config.max_width;
563
564         if break_line {
565             let indentation = make_indent(offset + self.config.tab_spaces);
566             result.push('\n');
567             result.push_str(&indentation);
568         }
569
570         let tactic = if break_line { ListTactic::Vertical } else { ListTactic::Horizontal };
571
572         // 1 = ,
573         let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
574         let fmt = ListFormatting {
575             tactic: tactic,
576             separator: ",",
577             trailing_separator: self.config.struct_trailing_comma,
578             indent: offset + self.config.tab_spaces,
579             h_width: self.config.max_width,
580             v_width: budget,
581             is_expression: false,
582         };
583
584         result.push_str(&write_list(&items, &fmt));
585
586         if break_line {
587             result.push('\n');
588             result.push_str(&make_indent(offset));
589         }
590
591         result.push_str(terminator);
592
593         if is_tuple {
594             result.push(';');
595         }
596
597         result
598     }
599
600     pub fn visit_struct(&mut self,
601                         ident: ast::Ident,
602                         vis: ast::Visibility,
603                         struct_def: &ast::StructDef,
604                         generics: &ast::Generics,
605                         span: Span)
606     {
607         let indent = self.block_indent;
608         let result = self.format_struct("struct ",
609                                         ident,
610                                         vis,
611                                         struct_def,
612                                         Some(generics),
613                                         span,
614                                         indent);
615         self.changes.push_str_span(span, &result);
616         self.last_pos = span.hi;
617     }
618
619     fn format_header(&self,
620                      item_name: &str,
621                      ident: ast::Ident,
622                      vis: ast::Visibility)
623         -> String
624     {
625         format!("{}{}{}", format_visibility(vis), item_name, &token::get_ident(ident))
626     }
627
628     fn format_generics(&self,
629                        generics: &ast::Generics,
630                        opener: &str,
631                        offset: usize,
632                        span: Span)
633         -> String
634     {
635         let mut result = self.rewrite_generics(generics, offset, span);
636
637         if generics.where_clause.predicates.len() > 0 || result.contains('\n') {
638             result.push_str(&self.rewrite_where_clause(&generics.where_clause,
639                                                        self.block_indent,
640                                                        span.hi));
641             result.push_str(&make_indent(self.block_indent));
642             result.push('\n');
643             result.push_str(opener.trim());
644         } else {
645             result.push_str(opener);
646         }
647
648         result
649     }
650
651     // Field of a struct
652     fn format_field(&self, field: &ast::StructField) -> String {
653         if contains_skip(&field.node.attrs) {
654             return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
655         }
656
657         let name = match field.node.kind {
658             ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
659             ast::StructFieldKind::UnnamedField(_) => None,
660         };
661         let vis = match field.node.kind {
662             ast::StructFieldKind::NamedField(_, vis) |
663             ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis)
664         };
665         let typ = pprust::ty_to_string(&field.node.ty);
666
667         let indent = self.block_indent + self.config.tab_spaces;
668         let mut attr_str = self.rewrite_attrs(&field.node.attrs, indent);
669         if attr_str.len() > 0 {
670             attr_str.push('\n');
671             attr_str.push_str(&make_indent(indent));
672         }
673
674         match name {
675             Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
676             None => format!("{}{}{}", attr_str, vis, typ)
677         }
678     }
679
680     fn rewrite_generics(&self, generics: &ast::Generics, offset: usize, span: Span) -> String {
681         // FIXME convert bounds to where clauses where they get too big or if
682         // there is a where clause at all.
683         let mut result = String::new();
684         let lifetimes: &[_] = &generics.lifetimes;
685         let tys: &[_] = &generics.ty_params;
686         if lifetimes.len() + tys.len() == 0 {
687             return result;
688         }
689
690         let budget = self.config.max_width - offset - 2;
691         // TODO might need to insert a newline if the generics are really long
692         result.push('<');
693
694         // Strings for the generics.
695         let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
696         let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
697
698         // Extract comments between generics.
699         let lt_spans = lifetimes.iter().map(|l| {
700             let hi = if l.bounds.len() == 0 {
701                 l.lifetime.span.hi
702             } else {
703                 l.bounds[l.bounds.len() - 1].span.hi
704             };
705             codemap::mk_sp(l.lifetime.span.lo, hi)
706         });
707         let ty_spans = tys.iter().map(span_for_ty_param);
708
709         let mut items = itemize_list(self.codemap,
710                                      Vec::new(),
711                                      lt_spans.chain(ty_spans),
712                                      ",",
713                                      ">",
714                                      |sp| sp.lo,
715                                      |sp| sp.hi,
716                                      |_| String::new(),
717                                      span_after(span, "<", self.codemap),
718                                      span.hi);
719
720         for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
721             item.item = ty;
722         }
723
724         let fmt = ListFormatting {
725             tactic: ListTactic::HorizontalVertical,
726             separator: ",",
727             trailing_separator: SeparatorTactic::Never,
728             indent: offset + 1,
729             h_width: budget,
730             v_width: budget,
731             is_expression: true,
732         };
733         result.push_str(&write_list(&items, &fmt));
734
735         result.push('>');
736
737         result
738     }
739
740     fn rewrite_where_clause(&self,
741                             where_clause: &ast::WhereClause,
742                             indent: usize,
743                             span_end: BytePos)
744         -> String
745     {
746         let mut result = String::new();
747         if where_clause.predicates.len() == 0 {
748             return result;
749         }
750
751         result.push('\n');
752         result.push_str(&make_indent(indent + 4));
753         result.push_str("where ");
754
755         let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
756         let items = itemize_list(self.codemap,
757                                  Vec::new(),
758                                  where_clause.predicates.iter(),
759                                  ",",
760                                  "{",
761                                  |pred| span_for_where_pred(pred).lo,
762                                  |pred| span_for_where_pred(pred).hi,
763                                  |pred| self.rewrite_pred(pred),
764                                  span_start,
765                                  span_end);
766
767         let budget = self.config.ideal_width + self.config.leeway - indent - 10;
768         let fmt = ListFormatting {
769             tactic: ListTactic::Vertical,
770             separator: ",",
771             trailing_separator: SeparatorTactic::Never,
772             indent: indent + 10,
773             h_width: budget,
774             v_width: budget,
775             is_expression: true,
776         };
777         result.push_str(&write_list(&items, &fmt));
778
779         result
780     }
781
782     fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
783         match *ret {
784             ast::FunctionRetTy::DefaultReturn(_) => String::new(),
785             ast::FunctionRetTy::NoReturn(_) => "-> !".to_owned(),
786             ast::FunctionRetTy::Return(ref ty) => "-> ".to_owned() + &pprust::ty_to_string(ty),
787         }
788     }
789
790     // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
791     fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
792         format!("{}: {}",
793                 pprust::pat_to_string(&arg.pat),
794                 pprust::ty_to_string(&arg.ty))
795     }
796 }
797
798 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
799     match *ret {
800         ast::FunctionRetTy::NoReturn(ref span) |
801         ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
802         ast::FunctionRetTy::Return(ref ty) => ty.span,
803     }
804 }
805
806 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
807     // Note that ty.span is the span for ty.ident, not the whole item.
808     let lo = ty.span.lo;
809     if let Some(ref def) = ty.default {
810         return codemap::mk_sp(lo, def.span.hi);
811     }
812     if ty.bounds.len() == 0 {
813         return ty.span;
814     }
815     let hi = match ty.bounds[ty.bounds.len() - 1] {
816         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
817         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
818     };
819     codemap::mk_sp(lo, hi)
820 }
821
822 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
823     match *pred {
824         ast::WherePredicate::BoundPredicate(ref p) => p.span,
825         ast::WherePredicate::RegionPredicate(ref p) => p.span,
826         ast::WherePredicate::EqPredicate(ref p) => p.span,
827     }
828 }