]> git.lizzy.rs Git - rust.git/blob - src/functions.rs
Comments on their own lines between args
[rust.git] / src / functions.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 use {ReturnIndent, MAX_WIDTH, BraceStyle,
12      IDEAL_WIDTH, LEEWAY, FN_BRACE_STYLE, FN_RETURN_INDENT};
13 use utils::make_indent;
14 use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
15 use visitor::FmtVisitor;
16 use syntax::{ast, abi};
17 use syntax::codemap::{self, Span, BytePos};
18 use syntax::print::pprust;
19 use syntax::parse::token;
20
21 impl<'a> FmtVisitor<'a> {
22     pub fn rewrite_fn(&mut self,
23                       indent: usize,
24                       ident: ast::Ident,
25                       fd: &ast::FnDecl,
26                       explicit_self: Option<&ast::ExplicitSelf>,
27                       generics: &ast::Generics,
28                       unsafety: &ast::Unsafety,
29                       abi: &abi::Abi,
30                       vis: ast::Visibility,
31                       next_span: Span) // next_span is a nasty hack, its a loose upper
32                                        // bound on any comments after the where clause.
33         -> String
34     {
35         // FIXME we'll lose any comments in between parts of the function decl, but anyone
36         // who comments there probably deserves what they get.
37
38         let where_clause = &generics.where_clause;
39         let newline_brace = self.newline_for_brace(where_clause);
40
41         let mut result = String::with_capacity(1024);
42         // Vis unsafety abi.
43         if vis == ast::Visibility::Public {
44             result.push_str("pub ");
45         }
46         if let &ast::Unsafety::Unsafe = unsafety {
47             result.push_str("unsafe ");
48         }
49         if *abi != abi::Rust {
50             result.push_str("extern ");
51             result.push_str(&abi.to_string());
52             result.push(' ');
53         }
54
55         // fn foo
56         result.push_str("fn ");
57         result.push_str(&token::get_ident(ident));
58
59         // Generics.
60         let generics_indent = indent + result.len();
61         result.push_str(&self.rewrite_generics(generics,
62                                                generics_indent,
63                                                span_for_return(&fd.output)));
64
65         let ret_str = self.rewrite_return(&fd.output);
66
67         // Args.
68         let (one_line_budget, multi_line_budget, arg_indent) =
69             self.compute_budgets_for_args(&mut result, indent, ret_str.len(), newline_brace);
70
71         debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
72                one_line_budget, multi_line_budget, arg_indent);
73
74         result.push('(');
75         result.push_str(&self.rewrite_args(&fd.inputs,
76                                            explicit_self,
77                                            one_line_budget,
78                                            multi_line_budget,
79                                            arg_indent,
80                                            span_for_return(&fd.output)));
81         result.push(')');
82
83         // Return type.
84         if ret_str.len() > 0 {
85             // If we've already gone multi-line, or the return type would push
86             // over the max width, then put the return type on a new line.
87             if result.contains("\n") ||
88                result.len() + indent + ret_str.len() > MAX_WIDTH {
89                 let indent = match FN_RETURN_INDENT {
90                     ReturnIndent::WithWhereClause => indent + 4,
91                     ReturnIndent::WithWhereClauseOrArgs if where_clause.predicates.len() > 0 => {
92                         indent + 4
93                     }
94                     // TODO we might want to check that using the arg indent doesn't
95                     // blow our budget, and if it does, then fallback to the where
96                     // clause indent.
97                     _ => arg_indent,
98                 };
99
100                 result.push('\n');
101                 result.push_str(&make_indent(indent));
102             } else {
103                 result.push(' ');
104             }
105             result.push_str(&ret_str);
106
107             // Comment between return type and the end of the decl.
108             let snippet_lo = fd.output.span().hi;
109             if where_clause.predicates.len() == 0 {
110                 let snippet_hi = next_span.lo;
111                 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
112                 let snippet = snippet.trim();
113                 if snippet.len() > 0 {
114                     result.push(' ');
115                     result.push_str(snippet);
116                 }
117             } else {
118                 // FIXME it would be nice to catch comments between the return type
119                 // and the where clause, but we don't have a span for the where
120                 // clause.
121             }
122         }
123
124         // Where clause.
125         result.push_str(&self.rewrite_where_clause(where_clause, indent, next_span));
126
127         // Prepare for the function body by possibly adding a newline and indent.
128         // FIXME we'll miss anything between the end of the signature and the start
129         // of the body, but we need more spans from the compiler to solve this.
130         if newline_brace {
131             result.push('\n');
132             result.push_str(&make_indent(self.block_indent));
133         } else {
134             result.push(' ');
135         }
136
137         result
138     }
139
140     fn rewrite_args(&self,
141                     args: &[ast::Arg],
142                     explicit_self: Option<&ast::ExplicitSelf>,
143                     one_line_budget: usize,
144                     multi_line_budget: usize,
145                     arg_indent: usize,
146                     ret_span: Span)
147         -> String
148     {
149         let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
150         // Account for sugary self.
151         let mut min_args = 1;
152         if let Some(explicit_self) = explicit_self {
153             match explicit_self.node {
154                 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
155                     let lt_str = match lt {
156                         &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
157                         &None => String::new(),
158                     };
159                     let mut_str = match m {
160                         &ast::Mutability::MutMutable => "mut ".to_string(),
161                         &ast::Mutability::MutImmutable => String::new(),
162                     };
163                     arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
164                     min_args = 2;
165                 }
166                 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
167                     arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
168                 }
169                 ast::ExplicitSelf_::SelfValue(_) => {
170                     arg_item_strs[0] = "self".to_string();
171                     min_args = 2;
172                 }
173                 _ => {}
174             }
175         }
176
177         // Comments between args
178         let mut arg_comments = Vec::new();
179         if min_args == 2 {
180             arg_comments.push("".to_string());
181         }
182         // TODO if there are no args, there might still be a comment, but without
183         // spans for the comment or parens, there is no chance of getting it right.
184         // You also don't get to put a comment on self, unless it is explicit.
185         if args.len() >= min_args {
186             arg_comments = self.make_comments_for_list(arg_comments,
187                                                        args[min_args-1..].iter(),
188                                                        ",",
189                                                        ")",
190                                                        |arg| arg.pat.span.lo,
191                                                        |arg| arg.ty.span.hi,
192                                                        ret_span.lo);
193         }
194
195         debug!("comments: {:?}", arg_comments);
196
197         // If there are // comments, keep them multi-line.
198         let mut list_tactic = ListTactic::HorizontalVertical;
199         if arg_comments.iter().any(|c| c.contains("//")) {
200             list_tactic = ListTactic::Vertical;
201         }
202
203         assert_eq!(arg_item_strs.len(), arg_comments.len());
204         let arg_strs: Vec<_> = arg_item_strs.into_iter().zip(arg_comments.into_iter()).collect();
205
206         let fmt = ListFormatting {
207             tactic: list_tactic,
208             separator: ",",
209             trailing_separator: SeparatorTactic::Never,
210             indent: arg_indent,
211             h_width: one_line_budget,
212             v_width: multi_line_budget,
213         };
214
215         write_list(&arg_strs, &fmt)
216     }
217
218     // Gets comments in between items of a list.
219     fn make_comments_for_list<T, I, F1, F2>(&self,
220                                             prefix: Vec<String>,
221                                             mut it: I,
222                                             separator: &str,
223                                             terminator: &str,
224                                             get_lo: F1,
225                                             get_hi: F2,
226                                             next_span_start: BytePos)
227         -> Vec<String>
228         where I: Iterator<Item=T>,
229               F1: Fn(&T) -> BytePos,
230               F2: Fn(&T) -> BytePos
231     {
232         let mut result = prefix;
233
234         let mut prev_end = get_hi(&it.next().unwrap());
235         for item in it {
236             let cur_start = get_lo(&item);
237             let snippet = self.snippet(codemap::mk_sp(prev_end, cur_start));
238             let mut snippet = snippet.trim();
239             let white_space: &[_] = &[' ', '\t'];
240             if snippet.starts_with(separator) {
241                 snippet = snippet[separator.len()..].trim_matches(white_space);
242             } else if snippet.ends_with(separator) {
243                 snippet = snippet[..snippet.len()-separator.len()].trim_matches(white_space);
244             }
245             result.push(snippet.to_string());
246             prev_end = get_hi(&item);
247         }
248         // Get the last commment.
249         // FIXME If you thought the crap with the commas was ugly, just wait.
250         // This is awful. We're going to look from the last item span to the
251         // start of the return type span, then we drop everything after the
252         // first closing paren. Obviously, this will break if there is a
253         // closing paren in the comment.
254         // The fix is comments in the AST or a span for the closing paren.
255         let snippet = self.snippet(codemap::mk_sp(prev_end, next_span_start));
256         let snippet = snippet.trim();
257         let snippet = &snippet[..snippet.find(terminator).unwrap_or(snippet.len())];
258         let snippet = snippet.trim();
259         result.push(snippet.to_string());
260
261         result
262     }
263
264     fn compute_budgets_for_args(&self,
265                                 result: &mut String,
266                                 indent: usize,
267                                 ret_str_len: usize,
268                                 newline_brace: bool)
269         -> (usize, usize, usize)
270     {
271         let mut budgets = None;
272
273         // Try keeping everything on the same line
274         if !result.contains("\n") {
275             // 3 = `() `, space is before ret_string
276             let mut used_space = indent + result.len() + ret_str_len + 3;
277             if !newline_brace {
278                 used_space += 2;
279             }
280             let one_line_budget = if used_space > MAX_WIDTH {
281                 0
282             } else {
283                 MAX_WIDTH - used_space
284             };
285
286             // 2 = `()`
287             let used_space = indent + result.len() + 2;
288             let max_space = IDEAL_WIDTH + LEEWAY;
289             debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
290                    used_space, max_space);
291             if used_space < max_space {
292                 budgets = Some((one_line_budget,
293                                 max_space - used_space,
294                                 indent + result.len() + 1));
295             }
296         }
297
298         // Didn't work. we must force vertical layout and put args on a newline.
299         if let None = budgets {
300             result.push('\n');
301             result.push_str(&make_indent(indent + 4));
302             // 6 = new indent + `()`
303             let used_space = indent + 6;
304             let max_space = IDEAL_WIDTH + LEEWAY;
305             if used_space > max_space {
306                 // Whoops! bankrupt.
307                 // TODO take evasive action, perhaps kill the indent or something.
308             } else {
309                 // 5 = new indent + `(`
310                 budgets = Some((0, max_space - used_space, indent + 5));
311             }
312         }
313
314         budgets.unwrap()
315     }
316
317     fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
318         match FN_BRACE_STYLE {
319             BraceStyle::AlwaysNextLine => true,
320             BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
321             _ => false,
322         }
323     }
324
325     fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, ret_span: Span) -> String {
326         // FIXME convert bounds to where clauses where they get too big or if
327         // there is a where clause at all.
328         let mut result = String::new();
329         let lifetimes: &[_] = &generics.lifetimes;
330         let tys: &[_] = &generics.ty_params;
331         if lifetimes.len() + tys.len() == 0 {
332             return result;
333         }
334
335         let budget = MAX_WIDTH - indent - 2;
336         // TODO might need to insert a newline if the generics are really long
337         result.push('<');
338
339         // Strings for the generics.
340         let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
341         let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
342
343         // Extract comments between generics.
344         let lt_spans = lifetimes.iter().map(|l| {
345             let hi = if l.bounds.len() == 0 {
346                 l.lifetime.span.hi
347             } else {
348                 l.bounds[l.bounds.len() - 1].span.hi
349             };
350             codemap::mk_sp(l.lifetime.span.lo, hi)
351         });
352         let ty_spans = tys.iter().map(span_for_ty_param);
353         let comments = self.make_comments_for_list(Vec::new(),
354                                                    lt_spans.chain(ty_spans),
355                                                    ",",
356                                                    ">",
357                                                    |sp| sp.lo,
358                                                    |sp| sp.hi,
359                                                    ret_span.lo);
360
361         // If there are // comments, keep them multi-line.
362         let mut list_tactic = ListTactic::HorizontalVertical;
363         if comments.iter().any(|c| c.contains("//")) {
364             list_tactic = ListTactic::Vertical;
365         }
366
367         let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
368         let fmt = ListFormatting {
369             tactic: list_tactic,
370             separator: ",",
371             trailing_separator: SeparatorTactic::Never,
372             indent: indent + 1,
373             h_width: budget,
374             v_width: budget,
375         };
376         result.push_str(&write_list(&generics_strs, &fmt));
377
378         result.push('>');
379
380         result
381     }
382
383     fn rewrite_where_clause(&self,
384                             where_clause: &ast::WhereClause,
385                             indent: usize,
386                             next_span: Span)
387         -> String
388     {
389         let mut result = String::new();
390         if where_clause.predicates.len() == 0 {
391             return result;
392         }
393
394         result.push('\n');
395         result.push_str(&make_indent(indent + 4));
396         result.push_str("where ");
397
398         let comments = self.make_comments_for_list(Vec::new(),
399                                                    where_clause.predicates.iter(),
400                                                    ",",
401                                                    "{",
402                                                    |pred| span_for_where_pred(pred).lo,
403                                                    |pred| span_for_where_pred(pred).hi,
404                                                    next_span.lo);
405         let where_strs: Vec<_> = where_clause.predicates.iter()
406                                                         .map(|p| (self.rewrite_pred(p)))
407                                                         .zip(comments.into_iter())
408                                                         .collect();
409
410         let budget = IDEAL_WIDTH + LEEWAY - indent - 10;
411         let fmt = ListFormatting {
412             tactic: ListTactic::Vertical,
413             separator: ",",
414             trailing_separator: SeparatorTactic::Never,
415             indent: indent + 10,
416             h_width: budget,
417             v_width: budget,
418         };
419         result.push_str(&write_list(&where_strs, &fmt));
420
421         result
422     }
423
424     fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
425         match *ret {
426             ast::FunctionRetTy::DefaultReturn(_) => String::new(),
427             ast::FunctionRetTy::NoReturn(_) => "-> !".to_string(),
428             ast::FunctionRetTy::Return(ref ty) => "-> ".to_string() + &pprust::ty_to_string(ty),
429         }
430     }
431
432     // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
433     fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
434         format!("{}: {}",
435                 pprust::pat_to_string(&arg.pat),
436                 pprust::ty_to_string(&arg.ty))
437     }
438 }
439
440 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
441     match *ret {
442         ast::FunctionRetTy::NoReturn(ref span) |
443         ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
444         ast::FunctionRetTy::Return(ref ty) => ty.span,
445     }
446 }
447
448 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
449     // Note that ty.span is the span for ty.ident, not the whole item.
450     let lo = ty.span.lo;
451     if let Some(ref def) = ty.default {
452         return codemap::mk_sp(lo, def.span.hi);
453     }
454     if ty.bounds.len() == 0 {
455         return ty.span;
456     }
457     let hi = match ty.bounds[ty.bounds.len() - 1] {
458         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
459         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
460     };
461     codemap::mk_sp(lo, hi)
462 }
463
464 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
465     match *pred {
466         ast::WherePredicate::BoundPredicate(ref p) => p.span,
467         ast::WherePredicate::RegionPredicate(ref p) => p.span,
468         ast::WherePredicate::EqPredicate(ref p) => p.span,
469     }
470 }