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, end_typaram};
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,
37 let newline_brace = self.newline_for_brace(&generics.where_clause);
39 let mut result = self.rewrite_fn_base(indent,
51 // Prepare for the function body by possibly adding a newline and indent.
52 // FIXME we'll miss anything between the end of the signature and the start
53 // of the body, but we need more spans from the compiler to solve this.
56 result.push_str(&make_indent(indent));
64 pub fn rewrite_required_fn(&mut self,
70 // Drop semicolon or it will be interpreted as comment
71 let span = codemap::mk_sp(span.lo, 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,
104 // FIXME we'll lose any comments in between parts of the function decl, but anyone
105 // who comments there probably deserves what they get.
107 let where_clause = &generics.where_clause;
109 let mut result = String::with_capacity(1024);
111 result.push_str(format_visibility(vis));
113 if let &ast::Unsafety::Unsafe = unsafety {
114 result.push_str("unsafe ");
116 if let &ast::Constness::Const = constness {
117 result.push_str("const ");
119 if *abi != abi::Rust {
120 result.push_str("extern ");
121 result.push_str(&abi.to_string());
126 result.push_str("fn ");
127 result.push_str(&token::get_ident(ident));
130 let generics_indent = indent + result.len();
131 result.push_str(&self.rewrite_generics(generics,
133 codemap::mk_sp(span.lo,
134 span_for_return(&fd.output).lo)));
136 let ret_str = self.rewrite_return(&fd.output);
139 let (one_line_budget, multi_line_budget, mut arg_indent) =
140 self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
142 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
143 one_line_budget, multi_line_budget, arg_indent);
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 {
149 result.push_str(&make_indent(arg_indent));
150 arg_indent = arg_indent + 1; // extra space for `(`
153 result.push_str("(\n");
154 result.push_str(&make_indent(arg_indent));
160 // A conservative estimation, to goal is to be over all parens in generics
161 let args_start = generics.ty_params
163 .map(|tp| end_typaram(tp))
165 let args_span = codemap::mk_sp(span_after(codemap::mk_sp(args_start, span.hi),
168 span_for_return(&fd.output).lo);
169 result.push_str(&self.rewrite_args(&fd.inputs,
178 if ret_str.len() > 0 {
179 // If we've already gone multi-line, or the return type would push
180 // over the max width, then put the return type on a new line.
181 if result.contains("\n") ||
182 result.len() + indent + ret_str.len() > self.config.max_width {
183 let indent = match self.config.fn_return_indent {
184 ReturnIndent::WithWhereClause => indent + 4,
185 // TODO we might want to check that using the arg indent doesn't
186 // blow our budget, and if it does, then fallback to the where
192 result.push_str(&make_indent(indent));
196 result.push_str(&ret_str);
198 // Comment between return type and the end of the decl.
199 let snippet_lo = fd.output.span().hi;
200 if where_clause.predicates.len() == 0 {
201 let snippet_hi = span.hi;
202 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
203 let snippet = snippet.trim();
204 if snippet.len() > 0 {
206 result.push_str(snippet);
209 // FIXME it would be nice to catch comments between the return type
210 // and the where clause, but we don't have a span for the where
216 result.push_str(&self.rewrite_where_clause(where_clause,
223 fn rewrite_args(&self,
225 explicit_self: Option<&ast::ExplicitSelf>,
226 one_line_budget: usize,
227 multi_line_budget: usize,
231 let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
232 // Account for sugary self.
233 let mut min_args = 1;
234 if let Some(explicit_self) = explicit_self {
235 match explicit_self.node {
236 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
237 let lt_str = match lt {
238 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
239 &None => String::new(),
241 let mut_str = match m {
242 &ast::Mutability::MutMutable => "mut ".to_owned(),
243 &ast::Mutability::MutImmutable => String::new(),
245 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
248 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
249 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
251 ast::ExplicitSelf_::SelfValue(_) => {
252 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
254 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
256 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
259 ast::Mutability::MutMutable => "mut ",
260 ast::Mutability::MutImmutable => "",
263 panic!("there is a bug or change in structure of AST, aborting.");
267 arg_item_strs[0] = format!("{}self", mut_str);
274 // Comments between args
275 let mut arg_items = Vec::new();
277 arg_items.push(ListItem::from_str(""));
280 // TODO if there are no args, there might still be a comment, but without
281 // spans for the comment or parens, there is no chance of getting it right.
282 // You also don't get to put a comment on self, unless it is explicit.
283 if args.len() >= min_args {
284 let comment_span_start = if min_args == 2 {
285 span_after(span, ",", self.codemap)
290 arg_items = itemize_list(self.codemap,
292 args[min_args-1..].iter(),
295 |arg| arg.pat.span.lo,
296 |arg| arg.ty.span.hi,
302 assert_eq!(arg_item_strs.len(), arg_items.len());
304 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
308 let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
310 trailing_separator: SeparatorTactic::Never,
312 h_width: one_line_budget,
313 v_width: multi_line_budget,
314 ends_with_newline: true, };
316 write_list(&arg_items, &fmt)
319 fn compute_budgets_for_args(&self,
324 -> (usize, usize, usize) {
325 let mut budgets = None;
327 // Try keeping everything on the same line
328 if !result.contains("\n") {
329 // 3 = `() `, space is before ret_string
330 let mut used_space = indent + result.len() + ret_str_len + 3;
334 let one_line_budget = if used_space > self.config.max_width {
337 self.config.max_width - used_space
341 let used_space = indent + result.len() + 2;
342 let max_space = self.config.ideal_width + self.config.leeway;
343 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
344 used_space, max_space);
345 if used_space < max_space {
346 budgets = Some((one_line_budget,
347 max_space - used_space,
348 indent + result.len() + 1));
352 // Didn't work. we must force vertical layout and put args on a newline.
353 if let None = budgets {
354 let new_indent = indent + self.config.tab_spaces;
355 let used_space = new_indent + 2; // account for `(` and `)`
356 let max_space = self.config.ideal_width + self.config.leeway;
357 if used_space > max_space {
359 // TODO take evasive action, perhaps kill the indent or something.
361 budgets = Some((0, max_space - used_space, new_indent));
368 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
369 match self.config.fn_brace_style {
370 BraceStyle::AlwaysNextLine => true,
371 BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
376 pub fn visit_enum(&mut self,
378 vis: ast::Visibility,
379 enum_def: &ast::EnumDef,
380 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, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
413 if self.visit_attrs(&field.node.attrs) {
417 self.format_missing_with_indent(field.span.lo);
419 let result = match field.node.kind {
420 ast::VariantKind::TupleVariantKind(ref types) => {
421 let vis = format_visibility(field.node.vis);
422 self.changes.push_str_span(field.span, vis);
423 let name = field.node.name.to_string();
424 self.changes.push_str_span(field.span, &name);
426 let mut result = String::new();
429 let items = itemize_list(self.codemap,
434 |arg| arg.ty.span.lo,
435 |arg| arg.ty.span.hi,
436 |arg| pprust::ty_to_string(&arg.ty),
437 span_after(field.span, "(", self.codemap),
442 let indent = self.block_indent
444 + field.node.name.to_string().len()
447 let comma_cost = if self.config.enum_trailing_comma { 1 } else { 0 };
448 let budget = self.config.ideal_width - indent - comma_cost - 1; // 1 = )
450 let fmt = ListFormatting {
451 tactic: ListTactic::HorizontalVertical,
453 trailing_separator: SeparatorTactic::Never,
457 ends_with_newline: false,
459 result.push_str(&write_list(&items, &fmt));
463 if let Some(ref expr) = field.node.disr_expr {
464 result.push_str(" = ");
465 let expr_snippet = self.snippet(expr.span);
466 result.push_str(&expr_snippet);
468 // Make sure we do not exceed column limit
470 assert!(self.config.max_width >= vis.len() + name.len() + expr_snippet.len() + 4,
471 "Enum variant exceeded column limit");
476 ast::VariantKind::StructVariantKind(ref struct_def) => {
477 // TODO Should limit the width, as we have a trailing comma
478 self.format_struct("",
487 self.changes.push_str_span(field.span, &result);
489 if !last_field || self.config.enum_trailing_comma {
490 self.changes.push_str_span(field.span, ",");
493 self.last_pos = field.span.hi + BytePos(1);
496 fn format_struct(&self,
499 vis: ast::Visibility,
500 struct_def: &ast::StructDef,
501 generics: Option<&ast::Generics>,
505 let mut result = String::with_capacity(1024);
507 let header_str = self.format_header(item_name, ident, vis);
508 result.push_str(&header_str);
510 if struct_def.fields.len() == 0 {
515 let is_tuple = match struct_def.fields[0].node.kind {
516 ast::StructFieldKind::NamedField(..) => false,
517 ast::StructFieldKind::UnnamedField(..) => true
520 let (opener, terminator) = if is_tuple { ("(", ")") } else { (" {", "}") };
522 let generics_str = match generics {
523 Some(g) => self.format_generics(g,
525 offset + header_str.len(),
526 codemap::mk_sp(span.lo,
527 struct_def.fields[0].span.lo)),
528 None => opener.to_owned()
530 result.push_str(&generics_str);
532 let items = itemize_list(self.codemap,
534 struct_def.fields.iter(),
538 // Include attributes and doc comments,
540 if field.node.attrs.len() > 0 {
541 field.node.attrs[0].span.lo
546 |field| field.node.ty.span.hi,
547 |field| self.format_field(field),
548 span_after(span, opener.trim(), self.codemap),
551 // 2 terminators and a semicolon
552 let used_budget = offset + header_str.len() + generics_str.len() + 3;
554 // Conservative approximation
555 let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
556 let break_line = !is_tuple || generics_str.contains('\n') ||
557 single_line_cost as usize + used_budget > self.config.max_width;
560 let indentation = make_indent(offset + self.config.tab_spaces);
562 result.push_str(&indentation);
565 let tactic = if break_line { ListTactic::Vertical } else { ListTactic::Horizontal };
568 let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
569 let fmt = ListFormatting { tactic: tactic,
571 trailing_separator: self.config.struct_trailing_comma,
572 indent: offset + self.config.tab_spaces,
573 h_width: self.config.max_width,
575 ends_with_newline: false, };
577 result.push_str(&write_list(&items, &fmt));
581 result.push_str(&make_indent(offset));
584 result.push_str(terminator);
593 pub fn visit_struct(&mut self,
595 vis: ast::Visibility,
596 struct_def: &ast::StructDef,
597 generics: &ast::Generics,
599 let indent = self.block_indent;
600 let result = self.format_struct("struct ",
607 self.changes.push_str_span(span, &result);
608 self.last_pos = span.hi;
611 fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
612 format!("{}{}{}", format_visibility(vis), item_name, &token::get_ident(ident))
615 fn format_generics(&self,
616 generics: &ast::Generics,
621 let mut result = self.rewrite_generics(generics, offset, span);
623 if generics.where_clause.predicates.len() > 0 || result.contains('\n') {
624 result.push_str(&self.rewrite_where_clause(&generics.where_clause,
627 result.push_str(&make_indent(self.block_indent));
629 result.push_str(opener.trim());
631 result.push_str(opener);
638 fn format_field(&self, field: &ast::StructField) -> String {
639 if contains_skip(&field.node.attrs) {
640 return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
643 let name = match field.node.kind {
644 ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
645 ast::StructFieldKind::UnnamedField(_) => None,
647 let vis = match field.node.kind {
648 ast::StructFieldKind::NamedField(_, vis) |
649 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis)
651 let typ = pprust::ty_to_string(&field.node.ty);
653 let indent = self.block_indent + self.config.tab_spaces;
654 let mut attr_str = self.rewrite_attrs(&field.node.attrs, indent);
655 if attr_str.len() > 0 {
657 attr_str.push_str(&make_indent(indent));
661 Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
662 None => format!("{}{}{}", attr_str, vis, typ)
666 fn rewrite_generics(&self, generics: &ast::Generics, offset: usize, span: Span) -> String {
667 // FIXME convert bounds to where clauses where they get too big or if
668 // there is a where clause at all.
669 let mut result = String::new();
670 let lifetimes: &[_] = &generics.lifetimes;
671 let tys: &[_] = &generics.ty_params;
672 if lifetimes.len() + tys.len() == 0 {
676 let budget = self.config.max_width - offset - 2;
677 // TODO might need to insert a newline if the generics are really long
680 // Strings for the generics.
681 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
682 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
684 // Extract comments between generics.
685 let lt_spans = lifetimes.iter().map(|l| {
686 let hi = if l.bounds.len() == 0 {
689 l.bounds[l.bounds.len() - 1].span.hi
691 codemap::mk_sp(l.lifetime.span.lo, hi)
693 let ty_spans = tys.iter().map(span_for_ty_param);
695 let mut items = itemize_list(self.codemap,
697 lt_spans.chain(ty_spans),
703 span_after(span, "<", self.codemap),
706 for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
710 let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
712 trailing_separator: SeparatorTactic::Never,
716 ends_with_newline: true, };
717 result.push_str(&write_list(&items, &fmt));
724 fn rewrite_where_clause(&self,
725 where_clause: &ast::WhereClause,
729 let mut result = String::new();
730 if where_clause.predicates.len() == 0 {
735 result.push_str(&make_indent(indent + 4));
736 result.push_str("where ");
738 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
739 let items = itemize_list(self.codemap,
741 where_clause.predicates.iter(),
744 |pred| span_for_where_pred(pred).lo,
745 |pred| span_for_where_pred(pred).hi,
746 |pred| self.rewrite_pred(pred),
750 let budget = self.config.ideal_width + self.config.leeway - indent - 10;
751 let fmt = ListFormatting { tactic: ListTactic::Vertical,
753 trailing_separator: SeparatorTactic::Never,
757 ends_with_newline: true, };
758 result.push_str(&write_list(&items, &fmt));
763 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
765 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
766 ast::FunctionRetTy::NoReturn(_) => "-> !".to_owned(),
767 ast::FunctionRetTy::Return(ref ty) => "-> ".to_owned() + &pprust::ty_to_string(ty),
771 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
772 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
774 pprust::pat_to_string(&arg.pat),
775 pprust::ty_to_string(&arg.ty))
779 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
781 ast::FunctionRetTy::NoReturn(ref span) |
782 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
783 ast::FunctionRetTy::Return(ref ty) => ty.span,
787 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
788 // Note that ty.span is the span for ty.ident, not the whole item.
790 if let Some(ref def) = ty.default {
791 return codemap::mk_sp(lo, def.span.hi);
793 if ty.bounds.len() == 0 {
796 let hi = match ty.bounds[ty.bounds.len() - 1] {
797 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
798 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
800 codemap::mk_sp(lo, hi)
803 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
805 ast::WherePredicate::BoundPredicate(ref p) => p.span,
806 ast::WherePredicate::RegionPredicate(ref p) => p.span,
807 ast::WherePredicate::EqPredicate(ref p) => p.span,