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