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 // Formatting top-level items - functions, structs, enums, traits, impls.
13 use {ReturnIndent, BraceStyle};
14 use utils::make_indent;
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;
22 impl<'a> FmtVisitor<'a> {
23 pub fn rewrite_fn(&mut self,
27 explicit_self: Option<&ast::ExplicitSelf>,
28 generics: &ast::Generics,
29 unsafety: &ast::Unsafety,
30 constness: &ast::Constness,
36 let newline_brace = self.newline_for_brace(&generics.where_clause);
38 let mut result = self.rewrite_fn_base(indent,
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.
55 result.push_str(&make_indent(indent));
63 pub fn rewrite_required_fn(&mut self,
70 // Drop semicolon or it will be interpreted as comment
71 let span_end = span.hi - BytePos(1);
73 let mut result = self.rewrite_fn_base(indent,
76 Some(&sig.explicit_self),
81 ast::Visibility::Inherited,
85 // Re-attach semicolon
91 fn rewrite_fn_base(&mut self,
95 explicit_self: Option<&ast::ExplicitSelf>,
96 generics: &ast::Generics,
97 unsafety: &ast::Unsafety,
98 constness: &ast::Constness,
100 vis: ast::Visibility,
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.
108 let where_clause = &generics.where_clause;
110 let mut result = String::with_capacity(1024);
112 if vis == ast::Visibility::Public {
113 result.push_str("pub ");
115 if let &ast::Unsafety::Unsafe = unsafety {
116 result.push_str("unsafe ");
118 if let &ast::Constness::Const = constness {
119 result.push_str("const ");
121 if *abi != abi::Rust {
122 result.push_str("extern ");
123 result.push_str(&abi.to_string());
128 result.push_str("fn ");
129 result.push_str(&token::get_ident(ident));
132 let generics_indent = indent + result.len();
133 result.push_str(&self.rewrite_generics(generics,
135 span_for_return(&fd.output).lo));
137 let ret_str = self.rewrite_return(&fd.output);
140 let (one_line_budget, multi_line_budget, mut arg_indent) =
141 self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
143 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
144 one_line_budget, multi_line_budget, arg_indent);
146 // Check if vertical layout was forced by compute_budget_for_args.
147 if one_line_budget <= 0 {
148 if config!(fn_args_paren_newline) {
150 result.push_str(&make_indent(arg_indent));
151 arg_indent = arg_indent + 1; // extra space for `(`
154 result.push_str("(\n");
155 result.push_str(&make_indent(arg_indent));
161 result.push_str(&self.rewrite_args(&fd.inputs,
166 span_for_return(&fd.output)));
170 if ret_str.len() > 0 {
171 // If we've already gone multi-line, or the return type would push
172 // over the max width, then put the return type on a new line.
173 if result.contains("\n") ||
174 result.len() + indent + ret_str.len() > config!(max_width) {
175 let indent = match config!(fn_return_indent) {
176 ReturnIndent::WithWhereClause => indent + 4,
177 // TODO we might want to check that using the arg indent doesn't
178 // blow our budget, and if it does, then fallback to the where
184 result.push_str(&make_indent(indent));
188 result.push_str(&ret_str);
190 // Comment between return type and the end of the decl.
191 let snippet_lo = fd.output.span().hi;
192 if where_clause.predicates.len() == 0 {
193 let snippet_hi = span_end;
194 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
195 let snippet = snippet.trim();
196 if snippet.len() > 0 {
198 result.push_str(snippet);
201 // FIXME it would be nice to catch comments between the return type
202 // and the where clause, but we don't have a span for the where
208 result.push_str(&self.rewrite_where_clause(where_clause, indent, span_end));
213 fn rewrite_args(&self,
215 explicit_self: Option<&ast::ExplicitSelf>,
216 one_line_budget: usize,
217 multi_line_budget: usize,
222 let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
223 // Account for sugary self.
224 let mut min_args = 1;
225 if let Some(explicit_self) = explicit_self {
226 match explicit_self.node {
227 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
228 let lt_str = match lt {
229 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
230 &None => String::new(),
232 let mut_str = match m {
233 &ast::Mutability::MutMutable => "mut ".to_owned(),
234 &ast::Mutability::MutImmutable => String::new(),
236 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
239 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
240 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
242 ast::ExplicitSelf_::SelfValue(_) => {
243 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
245 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
247 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
250 ast::Mutability::MutMutable => "mut ",
251 ast::Mutability::MutImmutable => "",
254 panic!("there is a bug or change in structure of AST, aborting.");
258 arg_item_strs[0] = format!("{}self", mut_str);
265 // Comments between args
266 let mut arg_comments = Vec::new();
268 arg_comments.push("".to_owned());
270 // TODO if there are no args, there might still be a comment, but without
271 // spans for the comment or parens, there is no chance of getting it right.
272 // You also don't get to put a comment on self, unless it is explicit.
273 if args.len() >= min_args {
274 arg_comments = self.make_comments_for_list(arg_comments,
275 args[min_args-1..].iter(),
278 |arg| arg.pat.span.lo,
279 |arg| arg.ty.span.hi,
283 debug!("comments: {:?}", arg_comments);
285 // If there are // comments, keep them multi-line.
286 let mut list_tactic = ListTactic::HorizontalVertical;
287 if arg_comments.iter().any(|c| c.contains("//")) {
288 list_tactic = ListTactic::Vertical;
291 assert_eq!(arg_item_strs.len(), arg_comments.len());
292 let arg_strs: Vec<_> = arg_item_strs.into_iter().zip(arg_comments.into_iter()).collect();
294 let fmt = ListFormatting {
297 trailing_separator: SeparatorTactic::Never,
299 h_width: one_line_budget,
300 v_width: multi_line_budget,
303 write_list(&arg_strs, &fmt)
306 // Gets comments in between items of a list.
307 fn make_comments_for_list<T, I, F1, F2>(&self,
314 next_span_start: BytePos)
316 where I: Iterator<Item=T>,
317 F1: Fn(&T) -> BytePos,
318 F2: Fn(&T) -> BytePos
320 let mut result = prefix;
322 let mut prev_end = get_hi(&it.next().unwrap());
324 let cur_start = get_lo(&item);
325 let snippet = self.snippet(codemap::mk_sp(prev_end, cur_start));
326 let mut snippet = snippet.trim();
327 let white_space: &[_] = &[' ', '\t'];
328 if snippet.starts_with(separator) {
329 snippet = snippet[separator.len()..].trim_matches(white_space);
330 } else if snippet.ends_with(separator) {
331 snippet = snippet[..snippet.len()-separator.len()].trim_matches(white_space);
333 result.push(snippet.to_owned());
334 prev_end = get_hi(&item);
336 // Get the last commment.
337 // FIXME If you thought the crap with the commas was ugly, just wait.
338 // This is awful. We're going to look from the last item span to the
339 // start of the return type span, then we drop everything after the
340 // first closing paren. Obviously, this will break if there is a
341 // closing paren in the comment.
342 // The fix is comments in the AST or a span for the closing paren.
343 let snippet = self.snippet(codemap::mk_sp(prev_end, next_span_start));
344 let snippet = snippet.trim();
345 let snippet = &snippet[..snippet.find(terminator)
346 .unwrap_or(snippet.find(separator).unwrap_or(snippet.len()))];
347 let snippet = snippet.trim();
348 result.push(snippet.to_owned());
353 fn compute_budgets_for_args(&self,
358 -> (usize, usize, usize)
360 let mut budgets = None;
362 // Try keeping everything on the same line
363 if !result.contains("\n") {
364 // 3 = `() `, space is before ret_string
365 let mut used_space = indent + result.len() + ret_str_len + 3;
369 let one_line_budget = if used_space > config!(max_width) {
372 config!(max_width) - used_space
376 let used_space = indent + result.len() + 2;
377 let max_space = config!(ideal_width) + config!(leeway);
378 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
379 used_space, max_space);
380 if used_space < max_space {
381 budgets = Some((one_line_budget,
382 max_space - used_space,
383 indent + result.len() + 1));
387 // Didn't work. we must force vertical layout and put args on a newline.
388 if let None = budgets {
389 let new_indent = indent + config!(tab_spaces);
390 let used_space = new_indent + 2; // account for `(` and `)`
391 let max_space = config!(ideal_width) + config!(leeway);
392 if used_space > max_space {
394 // TODO take evasive action, perhaps kill the indent or something.
396 budgets = Some((0, max_space - used_space, new_indent));
403 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
404 match config!(fn_brace_style) {
405 BraceStyle::AlwaysNextLine => true,
406 BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
411 pub fn visit_struct(&mut self,
413 vis: ast::Visibility,
414 struct_def: &ast::StructDef,
415 generics: &ast::Generics,
418 let header_str = self.struct_header(ident, vis);
419 self.changes.push_str_span(span, &header_str);
421 if struct_def.fields.len() == 0 {
422 assert!(generics.where_clause.predicates.len() == 0,
423 "No-field struct with where clause?");
424 assert!(generics.lifetimes.len() == 0, "No-field struct with generics?");
425 assert!(generics.ty_params.len() == 0, "No-field struct with generics?");
427 self.changes.push_str_span(span, ";");
431 let mut generics_buf = String::new();
432 let generics_str = self.rewrite_generics(generics, self.block_indent, struct_def.fields[0].span.lo);
433 generics_buf.push_str(&generics_str);
435 if generics.where_clause.predicates.len() > 0 {
436 generics_buf.push_str(&self.rewrite_where_clause(&generics.where_clause,
438 struct_def.fields[0].span.lo));
439 generics_buf.push_str(&make_indent(self.block_indent));
440 generics_buf.push_str("\n{");
443 generics_buf.push_str(" {");
445 self.changes.push_str_span(span, &generics_buf);
447 let struct_snippet = self.snippet(span);
448 // FIXME this will give incorrect results if there is a { in a commet.
449 self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1);
451 self.block_indent += config!(tab_spaces);
452 for (i, f) in struct_def.fields.iter().enumerate() {
453 self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
455 self.block_indent -= config!(tab_spaces);
457 self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
458 self.changes.push_str_span(span, "}");
461 fn struct_header(&self,
463 vis: ast::Visibility)
466 let vis = if vis == ast::Visibility::Public {
472 format!("{}struct {}", vis, &token::get_ident(ident))
476 fn visit_field(&mut self,
477 field: &ast::StructField,
479 // These two args are for missing spans hacks.
480 struct_start: BytePos,
481 struct_snippet: &str)
483 if self.visit_attrs(&field.node.attrs) {
486 self.format_missing_with_indent(field.span.lo);
488 let name = match field.node.kind {
489 ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
490 ast::StructFieldKind::UnnamedField(_) => None,
492 let vis = match field.node.kind {
493 ast::StructFieldKind::NamedField(_, vis) |
494 ast::StructFieldKind::UnnamedField(vis) => if vis == ast::Visibility::Public {
500 let typ = pprust::ty_to_string(&field.node.ty);
502 let mut field_str = match name {
504 let budget = config!(ideal_width) - self.block_indent;
505 // 3 is being conservative and assuming that there will be a trailing comma.
506 if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
507 format!("{}{}:\n{}{}",
510 &make_indent(self.block_indent + config!(tab_spaces)),
513 format!("{}{}: {}", vis, name, typ)
516 None => format!("{}{}", vis, typ),
518 if !last_field || config!(struct_trailing_comma) {
521 self.changes.push_str_span(field.span, &field_str);
523 // This hack makes sure we only add comments etc. after the comma, and
524 // makes sure we don't repeat any commas.
525 let hi = field.span.hi;
526 // FIXME a comma in a comment will break this hack.
527 let comma_pos = match struct_snippet[(hi.0 - struct_start.0) as usize..].find(',') {
531 self.last_pos = hi + BytePos(comma_pos as u32 + 1);
534 fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, span_end: BytePos) -> String {
535 // FIXME convert bounds to where clauses where they get too big or if
536 // there is a where clause at all.
537 let mut result = String::new();
538 let lifetimes: &[_] = &generics.lifetimes;
539 let tys: &[_] = &generics.ty_params;
540 if lifetimes.len() + tys.len() == 0 {
544 let budget = config!(max_width) - indent - 2;
545 // TODO might need to insert a newline if the generics are really long
548 // Strings for the generics.
549 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
550 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
552 // Extract comments between generics.
553 let lt_spans = lifetimes.iter().map(|l| {
554 let hi = if l.bounds.len() == 0 {
557 l.bounds[l.bounds.len() - 1].span.hi
559 codemap::mk_sp(l.lifetime.span.lo, hi)
561 let ty_spans = tys.iter().map(span_for_ty_param);
562 let comments = self.make_comments_for_list(Vec::new(),
563 lt_spans.chain(ty_spans),
570 // If there are // comments, keep them multi-line.
571 let mut list_tactic = ListTactic::HorizontalVertical;
572 if comments.iter().any(|c| c.contains("//")) {
573 list_tactic = ListTactic::Vertical;
576 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
577 let fmt = ListFormatting {
580 trailing_separator: SeparatorTactic::Never,
585 result.push_str(&write_list(&generics_strs, &fmt));
592 fn rewrite_where_clause(&self,
593 where_clause: &ast::WhereClause,
598 let mut result = String::new();
599 if where_clause.predicates.len() == 0 {
604 result.push_str(&make_indent(indent + 4));
605 result.push_str("where ");
607 let comments = self.make_comments_for_list(Vec::new(),
608 where_clause.predicates.iter(),
611 |pred| span_for_where_pred(pred).lo,
612 |pred| span_for_where_pred(pred).hi,
615 let where_strs: Vec<_> = where_clause.predicates.iter()
616 .map(|p| (self.rewrite_pred(p)))
617 .zip(comments.into_iter())
620 let budget = config!(ideal_width) + config!(leeway) - indent - 10;
621 let fmt = ListFormatting {
622 tactic: ListTactic::Vertical,
624 trailing_separator: SeparatorTactic::Never,
629 result.push_str(&write_list(&where_strs, &fmt));
634 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
636 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
637 ast::FunctionRetTy::NoReturn(_) => "-> !".to_owned(),
638 ast::FunctionRetTy::Return(ref ty) => "-> ".to_owned() + &pprust::ty_to_string(ty),
642 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
643 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
645 pprust::pat_to_string(&arg.pat),
646 pprust::ty_to_string(&arg.ty))
650 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
652 ast::FunctionRetTy::NoReturn(ref span) |
653 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
654 ast::FunctionRetTy::Return(ref ty) => ty.span,
658 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
659 // Note that ty.span is the span for ty.ident, not the whole item.
661 if let Some(ref def) = ty.default {
662 return codemap::mk_sp(lo, def.span.hi);
664 if ty.bounds.len() == 0 {
667 let hi = match ty.bounds[ty.bounds.len() - 1] {
668 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
669 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
671 codemap::mk_sp(lo, hi)
674 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
676 ast::WherePredicate::BoundPredicate(ref p) => p.span,
677 ast::WherePredicate::RegionPredicate(ref p) => p.span,
678 ast::WherePredicate::EqPredicate(ref p) => p.span,