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::{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;
19 use syntax::{ast, abi};
20 use syntax::codemap::{self, Span, BytePos};
21 use syntax::print::pprust;
22 use syntax::parse::token;
24 impl<'a> FmtVisitor<'a> {
25 pub fn rewrite_fn(&mut self,
29 explicit_self: Option<&ast::ExplicitSelf>,
30 generics: &ast::Generics,
31 unsafety: &ast::Unsafety,
32 constness: &ast::Constness,
38 let newline_brace = self.newline_for_brace(&generics.where_clause);
40 let mut result = self.rewrite_fn_base(indent,
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.
57 result.push_str(&make_indent(indent));
65 pub fn rewrite_required_fn(&mut self,
72 // Drop semicolon or it will be interpreted as comment
73 let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
75 let mut result = self.rewrite_fn_base(indent,
78 Some(&sig.explicit_self),
83 ast::Visibility::Inherited,
87 // Re-attach semicolon
93 fn rewrite_fn_base(&mut self,
97 explicit_self: Option<&ast::ExplicitSelf>,
98 generics: &ast::Generics,
99 unsafety: &ast::Unsafety,
100 constness: &ast::Constness,
102 vis: ast::Visibility,
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.
110 let where_clause = &generics.where_clause;
112 let mut result = String::with_capacity(1024);
114 result.push_str(format_visibility(vis));
116 if let &ast::Unsafety::Unsafe = unsafety {
117 result.push_str("unsafe ");
119 if let &ast::Constness::Const = constness {
120 result.push_str("const ");
122 if *abi != abi::Rust {
123 result.push_str("extern ");
124 result.push_str(&abi.to_string());
129 result.push_str("fn ");
130 result.push_str(&token::get_ident(ident));
133 let generics_indent = indent + result.len();
134 result.push_str(&self.rewrite_generics(generics,
136 codemap::mk_sp(span.lo,
137 span_for_return(&fd.output).lo)));
139 let ret_str = self.rewrite_return(&fd.output);
142 let (one_line_budget, multi_line_budget, mut arg_indent) =
143 self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
145 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
146 one_line_budget, multi_line_budget, arg_indent);
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 {
152 result.push_str(&make_indent(arg_indent));
153 arg_indent = arg_indent + 1; // extra space for `(`
156 result.push_str("(\n");
157 result.push_str(&make_indent(arg_indent));
163 result.push_str(&self.rewrite_args(&fd.inputs,
168 codemap::mk_sp(span_after(span, "(", self.codemap),
169 span_for_return(&fd.output).lo)));
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
187 result.push_str(&make_indent(indent));
191 result.push_str(&ret_str);
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 {
201 result.push_str(snippet);
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
211 result.push_str(&self.rewrite_where_clause(where_clause,
218 fn rewrite_args(&self,
220 explicit_self: Option<&ast::ExplicitSelf>,
221 one_line_budget: usize,
222 multi_line_budget: usize,
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(),
237 let mut_str = match m {
238 &ast::Mutability::MutMutable => "mut ".to_owned(),
239 &ast::Mutability::MutImmutable => String::new(),
241 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
244 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
245 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
247 ast::ExplicitSelf_::SelfValue(_) => {
248 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
250 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
252 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
255 ast::Mutability::MutMutable => "mut ",
256 ast::Mutability::MutImmutable => "",
259 panic!("there is a bug or change in structure of AST, aborting.");
263 arg_item_strs[0] = format!("{}self", mut_str);
270 // Comments between args
271 let mut arg_items = Vec::new();
273 arg_items.push(ListItem::from_str(""));
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)
286 arg_items = itemize_list(self.codemap,
288 args[min_args-1..].iter(),
291 |arg| arg.pat.span.lo,
292 |arg| arg.ty.span.hi,
298 assert_eq!(arg_item_strs.len(), arg_items.len());
300 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
304 let fmt = ListFormatting {
305 tactic: ListTactic::HorizontalVertical,
307 trailing_separator: SeparatorTactic::Never,
309 h_width: one_line_budget,
310 v_width: multi_line_budget,
314 write_list(&arg_items, &fmt)
317 fn compute_budgets_for_args(&self,
322 -> (usize, usize, usize)
324 let mut budgets = None;
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;
333 let one_line_budget = if used_space > self.config.max_width {
336 self.config.max_width - used_space
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));
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 {
358 // TODO take evasive action, perhaps kill the indent or something.
360 budgets = Some((0, max_space - used_space, new_indent));
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,
375 pub fn visit_enum(&mut self,
377 vis: ast::Visibility,
378 enum_def: &ast::EnumDef,
379 generics: &ast::Generics,
382 let header_str = self.format_header("enum ", ident, vis);
383 self.changes.push_str_span(span, &header_str);
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,
389 self.block_indent + self.config.tab_spaces,
390 codemap::mk_sp(span.lo,
392 self.changes.push_str_span(span, &generics_str);
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 {
400 enum_def.variants[i + 1].span.lo
403 self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
405 self.block_indent -= self.config.tab_spaces;
407 self.format_missing_with_indent(span.lo + BytePos(enum_snippet.rfind('}').unwrap() as u32));
408 self.changes.push_str_span(span, "}");
411 // Variant of an enum
412 fn visit_variant(&mut self,
413 field: &ast::Variant,
415 next_span_start: BytePos)
417 if self.visit_attrs(&field.node.attrs) {
421 self.format_missing_with_indent(field.span.lo);
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);
430 let mut result = String::new();
433 let items = itemize_list(self.codemap,
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),
446 let indent = self.block_indent
448 + field.node.name.to_string().len()
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 = )
454 let fmt = ListFormatting {
455 tactic: ListTactic::HorizontalVertical,
457 trailing_separator: SeparatorTactic::Never,
461 is_expression: false,
463 result.push_str(&write_list(&items, &fmt));
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);
472 // Make sure we do not exceed column limit
474 assert!(self.config.max_width >= vis.len() + name.len() + expr_snippet.len() + 4,
475 "Enum variant exceeded column limit");
478 self.changes.push_str_span(field.span, &result);
480 if !last_field || self.config.enum_trailing_comma {
481 self.changes.push_str_span(field.span, ",");
484 ast::VariantKind::StructVariantKind(ref struct_def) => {
485 let result = self.format_struct("",
493 self.changes.push_str_span(field.span, &result)
497 self.last_pos = field.span.hi + BytePos(1);
500 fn format_struct(&self,
503 vis: ast::Visibility,
504 struct_def: &ast::StructDef,
505 generics: Option<&ast::Generics>,
507 offset: usize) -> String
509 let mut result = String::with_capacity(1024);
511 let header_str = self.format_header(item_name, ident, vis);
512 result.push_str(&header_str);
514 if struct_def.fields.len() == 0 {
519 let is_tuple = match struct_def.fields[0].node.kind {
520 ast::StructFieldKind::NamedField(..) => false,
521 ast::StructFieldKind::UnnamedField(..) => true
524 let (opener, terminator) = if is_tuple { ("(", ")") } else { (" {", "}") };
526 let generics_str = match generics {
527 Some(g) => self.format_generics(g,
529 offset + header_str.len(),
530 codemap::mk_sp(span.lo,
531 struct_def.fields[0].span.lo)),
532 None => opener.to_owned()
534 result.push_str(&generics_str);
536 let items = itemize_list(self.codemap,
538 struct_def.fields.iter(),
542 // Include attributes and doc comments,
544 if field.node.attrs.len() > 0 {
545 field.node.attrs[0].span.lo
550 |field| field.node.ty.span.hi,
551 |field| self.format_field(field),
552 span_after(span, opener.trim(), self.codemap),
555 // 2 terminators and a semicolon
556 let used_budget = offset + header_str.len() + generics_str.len() + 3;
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;
565 let indentation = make_indent(offset + self.config.tab_spaces);
567 result.push_str(&indentation);
570 let tactic = if break_line { ListTactic::Vertical } else { ListTactic::Horizontal };
573 let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
574 let fmt = ListFormatting {
577 trailing_separator: self.config.struct_trailing_comma,
578 indent: offset + self.config.tab_spaces,
579 h_width: self.config.max_width,
581 is_expression: false,
584 result.push_str(&write_list(&items, &fmt));
588 result.push_str(&make_indent(offset));
591 result.push_str(terminator);
600 pub fn visit_struct(&mut self,
602 vis: ast::Visibility,
603 struct_def: &ast::StructDef,
604 generics: &ast::Generics,
607 let indent = self.block_indent;
608 let result = self.format_struct("struct ",
615 self.changes.push_str_span(span, &result);
616 self.last_pos = span.hi;
619 fn format_header(&self,
622 vis: ast::Visibility)
625 format!("{}{}{}", format_visibility(vis), item_name, &token::get_ident(ident))
628 fn format_generics(&self,
629 generics: &ast::Generics,
635 let mut result = self.rewrite_generics(generics, offset, span);
637 if generics.where_clause.predicates.len() > 0 || result.contains('\n') {
638 result.push_str(&self.rewrite_where_clause(&generics.where_clause,
641 result.push_str(&make_indent(self.block_indent));
643 result.push_str(opener.trim());
645 result.push_str(opener);
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));
657 let name = match field.node.kind {
658 ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
659 ast::StructFieldKind::UnnamedField(_) => None,
661 let vis = match field.node.kind {
662 ast::StructFieldKind::NamedField(_, vis) |
663 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis)
665 let typ = pprust::ty_to_string(&field.node.ty);
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 {
671 attr_str.push_str(&make_indent(indent));
675 Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
676 None => format!("{}{}{}", attr_str, vis, typ)
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 {
690 let budget = self.config.max_width - offset - 2;
691 // TODO might need to insert a newline if the generics are really long
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));
698 // Extract comments between generics.
699 let lt_spans = lifetimes.iter().map(|l| {
700 let hi = if l.bounds.len() == 0 {
703 l.bounds[l.bounds.len() - 1].span.hi
705 codemap::mk_sp(l.lifetime.span.lo, hi)
707 let ty_spans = tys.iter().map(span_for_ty_param);
709 let mut items = itemize_list(self.codemap,
711 lt_spans.chain(ty_spans),
717 span_after(span, "<", self.codemap),
720 for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
724 let fmt = ListFormatting {
725 tactic: ListTactic::HorizontalVertical,
727 trailing_separator: SeparatorTactic::Never,
733 result.push_str(&write_list(&items, &fmt));
740 fn rewrite_where_clause(&self,
741 where_clause: &ast::WhereClause,
746 let mut result = String::new();
747 if where_clause.predicates.len() == 0 {
752 result.push_str(&make_indent(indent + 4));
753 result.push_str("where ");
755 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
756 let items = itemize_list(self.codemap,
758 where_clause.predicates.iter(),
761 |pred| span_for_where_pred(pred).lo,
762 |pred| span_for_where_pred(pred).hi,
763 |pred| self.rewrite_pred(pred),
767 let budget = self.config.ideal_width + self.config.leeway - indent - 10;
768 let fmt = ListFormatting {
769 tactic: ListTactic::Vertical,
771 trailing_separator: SeparatorTactic::Never,
777 result.push_str(&write_list(&items, &fmt));
782 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
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),
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 {
793 pprust::pat_to_string(&arg.pat),
794 pprust::ty_to_string(&arg.ty))
798 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
800 ast::FunctionRetTy::NoReturn(ref span) |
801 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
802 ast::FunctionRetTy::Return(ref ty) => ty.span,
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.
809 if let Some(ref def) = ty.default {
810 return codemap::mk_sp(lo, def.span.hi);
812 if ty.bounds.len() == 0 {
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,
819 codemap::mk_sp(lo, hi)
822 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
824 ast::WherePredicate::BoundPredicate(ref p) => p.span,
825 ast::WherePredicate::RegionPredicate(ref p) => p.span,
826 ast::WherePredicate::EqPredicate(ref p) => p.span,