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.
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.
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;
21 impl<'a> FmtVisitor<'a> {
22 pub fn rewrite_fn(&mut self,
26 explicit_self: Option<&ast::ExplicitSelf>,
27 generics: &ast::Generics,
28 unsafety: &ast::Unsafety,
31 next_span: Span) // next_span is a nasty hack, its a loose upper
32 // bound on any comments after the where clause.
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.
38 let where_clause = &generics.where_clause;
39 let newline_brace = self.newline_for_brace(where_clause);
41 let mut result = String::with_capacity(1024);
43 if vis == ast::Visibility::Public {
44 result.push_str("pub ");
46 if let &ast::Unsafety::Unsafe = unsafety {
47 result.push_str("unsafe ");
49 if *abi != abi::Rust {
50 result.push_str("extern ");
51 result.push_str(&abi.to_string());
56 result.push_str("fn ");
57 result.push_str(&token::get_ident(ident));
60 let generics_indent = indent + result.len();
61 result.push_str(&self.rewrite_generics(generics,
63 span_for_return(&fd.output)));
65 let ret_str = self.rewrite_return(&fd.output);
68 let (one_line_budget, multi_line_budget, arg_indent) =
69 self.compute_budgets_for_args(&mut result, indent, ret_str.len(), newline_brace);
71 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
72 one_line_budget, multi_line_budget, arg_indent);
75 result.push_str(&self.rewrite_args(&fd.inputs,
80 span_for_return(&fd.output)));
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 // TODO we might want to check that using the arg indent doesn't
92 // blow our budget, and if it does, then fallback to the where
98 result.push_str(&make_indent(indent));
102 result.push_str(&ret_str);
104 // Comment between return type and the end of the decl.
105 let snippet_lo = fd.output.span().hi;
106 if where_clause.predicates.len() == 0 {
107 let snippet_hi = next_span.lo;
108 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
109 let snippet = snippet.trim();
110 if snippet.len() > 0 {
112 result.push_str(snippet);
115 // FIXME it would be nice to catch comments between the return type
116 // and the where clause, but we don't have a span for the where
122 result.push_str(&self.rewrite_where_clause(where_clause, indent, next_span));
124 // Prepare for the function body by possibly adding a newline and indent.
125 // FIXME we'll miss anything between the end of the signature and the start
126 // of the body, but we need more spans from the compiler to solve this.
129 result.push_str(&make_indent(self.block_indent));
137 fn rewrite_args(&self,
139 explicit_self: Option<&ast::ExplicitSelf>,
140 one_line_budget: usize,
141 multi_line_budget: usize,
146 let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
147 // Account for sugary self.
148 let mut min_args = 1;
149 if let Some(explicit_self) = explicit_self {
150 match explicit_self.node {
151 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
152 let lt_str = match lt {
153 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
154 &None => String::new(),
156 let mut_str = match m {
157 &ast::Mutability::MutMutable => "mut ".to_string(),
158 &ast::Mutability::MutImmutable => String::new(),
160 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
163 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
164 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
166 ast::ExplicitSelf_::SelfValue(_) => {
167 arg_item_strs[0] = "self".to_string();
174 // Comments between args
175 let mut arg_comments = Vec::new();
177 arg_comments.push("".to_string());
179 // TODO if there are no args, there might still be a comment, but without
180 // spans for the comment or parens, there is no chance of getting it right.
181 // You also don't get to put a comment on self, unless it is explicit.
182 if args.len() >= min_args {
183 arg_comments = self.make_comments_for_list(arg_comments,
184 args[min_args-1..].iter(),
187 |arg| arg.pat.span.lo,
188 |arg| arg.ty.span.hi,
192 debug!("comments: {:?}", arg_comments);
194 // If there are // comments, keep them multi-line.
195 let mut list_tactic = ListTactic::HorizontalVertical;
196 if arg_comments.iter().any(|c| c.contains("//")) {
197 list_tactic = ListTactic::Vertical;
200 assert_eq!(arg_item_strs.len(), arg_comments.len());
201 let arg_strs: Vec<_> = arg_item_strs.into_iter().zip(arg_comments.into_iter()).collect();
203 let fmt = ListFormatting {
206 trailing_separator: SeparatorTactic::Never,
208 h_width: one_line_budget,
209 v_width: multi_line_budget,
212 write_list(&arg_strs, &fmt)
215 // Gets comments in between items of a list.
216 fn make_comments_for_list<T, I, F1, F2>(&self,
223 next_span_start: BytePos)
225 where I: Iterator<Item=T>,
226 F1: Fn(&T) -> BytePos,
227 F2: Fn(&T) -> BytePos
229 let mut result = prefix;
231 let mut prev_end = get_hi(&it.next().unwrap());
233 let cur_start = get_lo(&item);
234 let snippet = self.snippet(codemap::mk_sp(prev_end, cur_start));
235 let mut snippet = snippet.trim();
236 let white_space: &[_] = &[' ', '\t'];
237 if snippet.starts_with(separator) {
238 snippet = snippet[separator.len()..].trim_matches(white_space);
239 } else if snippet.ends_with(separator) {
240 snippet = snippet[..snippet.len()-separator.len()].trim_matches(white_space);
242 result.push(snippet.to_string());
243 prev_end = get_hi(&item);
245 // Get the last commment.
246 // FIXME If you thought the crap with the commas was ugly, just wait.
247 // This is awful. We're going to look from the last item span to the
248 // start of the return type span, then we drop everything after the
249 // first closing paren. Obviously, this will break if there is a
250 // closing paren in the comment.
251 // The fix is comments in the AST or a span for the closing paren.
252 let snippet = self.snippet(codemap::mk_sp(prev_end, next_span_start));
253 let snippet = snippet.trim();
254 let snippet = &snippet[..snippet.find(terminator)
255 .unwrap_or(snippet.find(separator).unwrap_or(snippet.len()))];
256 let snippet = snippet.trim();
257 result.push(snippet.to_string());
262 fn compute_budgets_for_args(&self,
267 -> (usize, usize, usize)
269 let mut budgets = None;
271 // Try keeping everything on the same line
272 if !result.contains("\n") {
273 // 3 = `() `, space is before ret_string
274 let mut used_space = indent + result.len() + ret_str_len + 3;
278 let one_line_budget = if used_space > MAX_WIDTH {
281 MAX_WIDTH - used_space
285 let used_space = indent + result.len() + 2;
286 let max_space = IDEAL_WIDTH + LEEWAY;
287 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
288 used_space, max_space);
289 if used_space < max_space {
290 budgets = Some((one_line_budget,
291 max_space - used_space,
292 indent + result.len() + 1));
296 // Didn't work. we must force vertical layout and put args on a newline.
297 if let None = budgets {
299 result.push_str(&make_indent(indent + 4));
300 // 6 = new indent + `()`
301 let used_space = indent + 6;
302 let max_space = IDEAL_WIDTH + LEEWAY;
303 if used_space > max_space {
305 // TODO take evasive action, perhaps kill the indent or something.
307 // 5 = new indent + `(`
308 budgets = Some((0, max_space - used_space, indent + 5));
315 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
316 match FN_BRACE_STYLE {
317 BraceStyle::AlwaysNextLine => true,
318 BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
323 fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, ret_span: Span) -> String {
324 // FIXME convert bounds to where clauses where they get too big or if
325 // there is a where clause at all.
326 let mut result = String::new();
327 let lifetimes: &[_] = &generics.lifetimes;
328 let tys: &[_] = &generics.ty_params;
329 if lifetimes.len() + tys.len() == 0 {
333 let budget = MAX_WIDTH - indent - 2;
334 // TODO might need to insert a newline if the generics are really long
337 // Strings for the generics.
338 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
339 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
341 // Extract comments between generics.
342 let lt_spans = lifetimes.iter().map(|l| {
343 let hi = if l.bounds.len() == 0 {
346 l.bounds[l.bounds.len() - 1].span.hi
348 codemap::mk_sp(l.lifetime.span.lo, hi)
350 let ty_spans = tys.iter().map(span_for_ty_param);
351 let comments = self.make_comments_for_list(Vec::new(),
352 lt_spans.chain(ty_spans),
359 // If there are // comments, keep them multi-line.
360 let mut list_tactic = ListTactic::HorizontalVertical;
361 if comments.iter().any(|c| c.contains("//")) {
362 list_tactic = ListTactic::Vertical;
365 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
366 let fmt = ListFormatting {
369 trailing_separator: SeparatorTactic::Never,
374 result.push_str(&write_list(&generics_strs, &fmt));
381 fn rewrite_where_clause(&self,
382 where_clause: &ast::WhereClause,
387 let mut result = String::new();
388 if where_clause.predicates.len() == 0 {
393 result.push_str(&make_indent(indent + 4));
394 result.push_str("where ");
396 let comments = self.make_comments_for_list(Vec::new(),
397 where_clause.predicates.iter(),
400 |pred| span_for_where_pred(pred).lo,
401 |pred| span_for_where_pred(pred).hi,
403 let where_strs: Vec<_> = where_clause.predicates.iter()
404 .map(|p| (self.rewrite_pred(p)))
405 .zip(comments.into_iter())
408 let budget = IDEAL_WIDTH + LEEWAY - indent - 10;
409 let fmt = ListFormatting {
410 tactic: ListTactic::Vertical,
412 trailing_separator: SeparatorTactic::Never,
417 result.push_str(&write_list(&where_strs, &fmt));
422 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
424 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
425 ast::FunctionRetTy::NoReturn(_) => "-> !".to_string(),
426 ast::FunctionRetTy::Return(ref ty) => "-> ".to_string() + &pprust::ty_to_string(ty),
430 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
431 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
433 pprust::pat_to_string(&arg.pat),
434 pprust::ty_to_string(&arg.ty))
438 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
440 ast::FunctionRetTy::NoReturn(ref span) |
441 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
442 ast::FunctionRetTy::Return(ref ty) => ty.span,
446 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
447 // Note that ty.span is the span for ty.ident, not the whole item.
449 if let Some(ref def) = ty.default {
450 return codemap::mk_sp(lo, def.span.hi);
452 if ty.bounds.len() == 0 {
455 let hi = match ty.bounds[ty.bounds.len() - 1] {
456 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
457 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
459 codemap::mk_sp(lo, hi)
462 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
464 ast::WherePredicate::BoundPredicate(ref p) => p.span,
465 ast::WherePredicate::RegionPredicate(ref p) => p.span,
466 ast::WherePredicate::EqPredicate(ref p) => p.span,