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};
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 result.push_str(format_visibility(vis));
114 if let &ast::Unsafety::Unsafe = unsafety {
115 result.push_str("unsafe ");
117 if let &ast::Constness::Const = constness {
118 result.push_str("const ");
120 if *abi != abi::Rust {
121 result.push_str("extern ");
122 result.push_str(&abi.to_string());
127 result.push_str("fn ");
128 result.push_str(&token::get_ident(ident));
131 let generics_indent = indent + result.len();
132 result.push_str(&self.rewrite_generics(generics,
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 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 result.push_str(&self.rewrite_args(&fd.inputs,
165 span_for_return(&fd.output)));
169 if ret_str.len() > 0 {
170 // If we've already gone multi-line, or the return type would push
171 // over the max width, then put the return type on a new line.
172 if result.contains("\n") ||
173 result.len() + indent + ret_str.len() > config!(max_width) {
174 let indent = match config!(fn_return_indent) {
175 ReturnIndent::WithWhereClause => indent + 4,
176 // TODO we might want to check that using the arg indent doesn't
177 // blow our budget, and if it does, then fallback to the where
183 result.push_str(&make_indent(indent));
187 result.push_str(&ret_str);
189 // Comment between return type and the end of the decl.
190 let snippet_lo = fd.output.span().hi;
191 if where_clause.predicates.len() == 0 {
192 let snippet_hi = span_end;
193 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
194 let snippet = snippet.trim();
195 if snippet.len() > 0 {
197 result.push_str(snippet);
200 // FIXME it would be nice to catch comments between the return type
201 // and the where clause, but we don't have a span for the where
207 result.push_str(&self.rewrite_where_clause(where_clause, indent, span_end));
212 fn rewrite_args(&self,
214 explicit_self: Option<&ast::ExplicitSelf>,
215 one_line_budget: usize,
216 multi_line_budget: usize,
221 let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
222 // Account for sugary self.
223 let mut min_args = 1;
224 if let Some(explicit_self) = explicit_self {
225 match explicit_self.node {
226 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
227 let lt_str = match lt {
228 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
229 &None => String::new(),
231 let mut_str = match m {
232 &ast::Mutability::MutMutable => "mut ".to_owned(),
233 &ast::Mutability::MutImmutable => String::new(),
235 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
238 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
239 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
241 ast::ExplicitSelf_::SelfValue(_) => {
242 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
244 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
246 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
249 ast::Mutability::MutMutable => "mut ",
250 ast::Mutability::MutImmutable => "",
253 panic!("there is a bug or change in structure of AST, aborting.");
257 arg_item_strs[0] = format!("{}self", mut_str);
264 // Comments between args
265 let mut arg_comments = Vec::new();
267 arg_comments.push("".to_owned());
269 // TODO if there are no args, there might still be a comment, but without
270 // spans for the comment or parens, there is no chance of getting it right.
271 // You also don't get to put a comment on self, unless it is explicit.
272 if args.len() >= min_args {
273 arg_comments = self.make_comments_for_list(arg_comments,
274 args[min_args-1..].iter(),
277 |arg| arg.pat.span.lo,
278 |arg| arg.ty.span.hi,
282 debug!("comments: {:?}", arg_comments);
284 // If there are // comments, keep them multi-line.
285 let mut list_tactic = ListTactic::HorizontalVertical;
286 if arg_comments.iter().any(|c| c.contains("//")) {
287 list_tactic = ListTactic::Vertical;
290 assert_eq!(arg_item_strs.len(), arg_comments.len());
291 let arg_strs: Vec<_> = arg_item_strs.into_iter().zip(arg_comments.into_iter()).collect();
293 let fmt = ListFormatting {
296 trailing_separator: SeparatorTactic::Never,
298 h_width: one_line_budget,
299 v_width: multi_line_budget,
302 write_list(&arg_strs, &fmt)
305 // Gets comments in between items of a list.
306 fn make_comments_for_list<T, I, F1, F2>(&self,
313 next_span_start: BytePos)
315 where I: Iterator<Item=T>,
316 F1: Fn(&T) -> BytePos,
317 F2: Fn(&T) -> BytePos
319 let mut result = prefix;
321 let mut prev_end = get_hi(&it.next().unwrap());
323 let cur_start = get_lo(&item);
324 let snippet = self.snippet(codemap::mk_sp(prev_end, cur_start));
325 let mut snippet = snippet.trim();
326 let white_space: &[_] = &[' ', '\t'];
327 if snippet.starts_with(separator) {
328 snippet = snippet[separator.len()..].trim_matches(white_space);
329 } else if snippet.ends_with(separator) {
330 snippet = snippet[..snippet.len()-separator.len()].trim_matches(white_space);
332 result.push(snippet.to_owned());
333 prev_end = get_hi(&item);
335 // Get the last commment.
336 // FIXME If you thought the crap with the commas was ugly, just wait.
337 // This is awful. We're going to look from the last item span to the
338 // start of the return type span, then we drop everything after the
339 // first closing paren. Obviously, this will break if there is a
340 // closing paren in the comment.
341 // The fix is comments in the AST or a span for the closing paren.
342 let snippet = self.snippet(codemap::mk_sp(prev_end, next_span_start));
343 let snippet = snippet.trim();
344 let snippet = &snippet[..snippet.find(terminator).unwrap_or(snippet.len())];
345 let snippet = snippet.trim();
346 result.push(snippet.to_owned());
351 fn compute_budgets_for_args(&self,
356 -> (usize, usize, usize)
358 let mut budgets = None;
360 // Try keeping everything on the same line
361 if !result.contains("\n") {
362 // 3 = `() `, space is before ret_string
363 let mut used_space = indent + result.len() + ret_str_len + 3;
367 let one_line_budget = if used_space > config!(max_width) {
370 config!(max_width) - used_space
374 let used_space = indent + result.len() + 2;
375 let max_space = config!(ideal_width) + config!(leeway);
376 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
377 used_space, max_space);
378 if used_space < max_space {
379 budgets = Some((one_line_budget,
380 max_space - used_space,
381 indent + result.len() + 1));
385 // Didn't work. we must force vertical layout and put args on a newline.
386 if let None = budgets {
387 let new_indent = indent + config!(tab_spaces);
388 let used_space = new_indent + 2; // account for `(` and `)`
389 let max_space = config!(ideal_width) + config!(leeway);
390 if used_space > max_space {
392 // TODO take evasive action, perhaps kill the indent or something.
394 budgets = Some((0, max_space - used_space, new_indent));
401 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
402 match config!(fn_brace_style) {
403 BraceStyle::AlwaysNextLine => true,
404 BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
409 pub fn visit_enum(&mut self,
411 vis: ast::Visibility,
412 enum_def: &ast::EnumDef,
413 generics: &ast::Generics,
416 let header_str = self.format_header("enum", ident, vis);
417 self.changes.push_str_span(span, &header_str);
419 let enum_snippet = self.snippet(span);
420 // FIXME this will give incorrect results if there is a { in a comment.
421 let body_start = span.lo + BytePos(enum_snippet.find('{').unwrap() as u32 + 1);
422 let generics_str = self.format_generics(generics, body_start);
423 self.changes.push_str_span(span, &generics_str);
425 self.last_pos = body_start;
426 self.block_indent += config!(tab_spaces);
427 for (i, f) in enum_def.variants.iter().enumerate() {
428 let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
431 enum_def.variants[i + 1].span.lo
434 self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
436 self.block_indent -= config!(tab_spaces);
438 self.format_missing_with_indent(span.lo + BytePos(enum_snippet.rfind('}').unwrap() as u32));
439 self.changes.push_str_span(span, "}");
442 // Variant of an enum
443 fn visit_variant(&mut self,
444 field: &ast::Variant,
446 next_span_start: BytePos)
448 if self.visit_attrs(&field.node.attrs) {
452 if let ast::VariantKind::TupleVariantKind(ref types) = field.node.kind {
453 self.format_missing_with_indent(field.span.lo);
455 let vis = format_visibility(field.node.vis);
456 self.changes.push_str_span(field.span, vis);
457 let name = field.node.name.to_string();
458 self.changes.push_str_span(field.span, &name);
460 let mut result = String::new();
463 let comments = self.make_comments_for_list(Vec::new(),
464 types.iter().map(|arg| arg.ty.span),
471 let type_strings: Vec<_> = types.iter()
472 .map(|arg| pprust::ty_to_string(&arg.ty))
473 .zip(comments.into_iter())
478 let indent = self.block_indent
480 + field.node.name.to_string().len()
483 let comma_cost = if config!(enum_trailing_comma) { 1 } else { 0 };
484 let budget = config!(ideal_width) - indent - comma_cost - 1; // 1 = )
486 let fmt = ListFormatting {
487 tactic: ListTactic::HorizontalVertical,
489 trailing_separator: SeparatorTactic::Never,
494 result.push_str(&write_list(&type_strings, &fmt));
498 if let Some(ref expr) = field.node.disr_expr {
499 result.push_str(" = ");
500 let expr_snippet = self.snippet(expr.span);
501 result.push_str(&expr_snippet);
503 // Make sure we do not exceed column limit
505 assert!(config!(max_width) >= vis.len() + name.len() + expr_snippet.len() + 4,
506 "Enum variant exceeded column limit");
509 self.changes.push_str_span(field.span, &result);
511 if !last_field || config!(enum_trailing_comma) {
512 self.changes.push_str_span(field.span, ",");
516 // TODO: deal with struct-like variants
518 self.last_pos = field.span.hi + BytePos(1);
521 pub fn visit_struct(&mut self,
523 vis: ast::Visibility,
524 struct_def: &ast::StructDef,
525 generics: &ast::Generics,
528 let header_str = self.format_header("struct", ident, vis);
529 self.changes.push_str_span(span, &header_str);
531 if struct_def.fields.len() == 0 {
532 assert!(generics.where_clause.predicates.len() == 0,
533 "No-field struct with where clause?");
534 assert!(generics.lifetimes.len() == 0, "No-field struct with generics?");
535 assert!(generics.ty_params.len() == 0, "No-field struct with generics?");
537 self.changes.push_str_span(span, ";");
541 let generics_str = self.format_generics(generics, struct_def.fields[0].span.lo);
542 self.changes.push_str_span(span, &generics_str);
544 let struct_snippet = self.snippet(span);
545 // FIXME this will give incorrect results if there is a { in a comment.
546 self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1);
548 self.block_indent += config!(tab_spaces);
549 for (i, f) in struct_def.fields.iter().enumerate() {
550 self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
552 self.block_indent -= config!(tab_spaces);
554 self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
555 self.changes.push_str_span(span, "}");
558 fn format_header(&self,
561 vis: ast::Visibility)
564 format!("{}{} {}", format_visibility(vis), item_name, &token::get_ident(ident))
567 fn format_generics(&self,
568 generics: &ast::Generics,
572 let mut result = self.rewrite_generics(generics, self.block_indent, span_end);
574 if generics.where_clause.predicates.len() > 0 {
575 result.push_str(&self.rewrite_where_clause(&generics.where_clause,
578 result.push_str(&make_indent(self.block_indent));
579 result.push_str("\n{");
582 result.push_str(" {");
589 fn visit_field(&mut self,
590 field: &ast::StructField,
592 // These two args are for missing spans hacks.
593 struct_start: BytePos,
594 struct_snippet: &str)
596 if self.visit_attrs(&field.node.attrs) {
599 self.format_missing_with_indent(field.span.lo);
601 let name = match field.node.kind {
602 ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
603 ast::StructFieldKind::UnnamedField(_) => None,
605 let vis = match field.node.kind {
606 ast::StructFieldKind::NamedField(_, vis) |
607 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis)
609 let typ = pprust::ty_to_string(&field.node.ty);
611 let mut field_str = match name {
613 let budget = config!(ideal_width) - self.block_indent;
614 // 3 is being conservative and assuming that there will be a trailing comma.
615 if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
616 format!("{}{}:\n{}{}",
619 &make_indent(self.block_indent + config!(tab_spaces)),
622 format!("{}{}: {}", vis, name, typ)
625 None => format!("{}{}", vis, typ),
627 if !last_field || config!(struct_trailing_comma) {
630 self.changes.push_str_span(field.span, &field_str);
632 // This hack makes sure we only add comments etc. after the comma, and
633 // makes sure we don't repeat any commas.
634 let hi = field.span.hi;
635 // FIXME a comma in a comment will break this hack.
636 let comma_pos = match struct_snippet[(hi.0 - struct_start.0) as usize..].find(',') {
640 self.last_pos = hi + BytePos(comma_pos as u32 + 1);
643 fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, span_end: BytePos) -> String {
644 // FIXME convert bounds to where clauses where they get too big or if
645 // there is a where clause at all.
646 let mut result = String::new();
647 let lifetimes: &[_] = &generics.lifetimes;
648 let tys: &[_] = &generics.ty_params;
649 if lifetimes.len() + tys.len() == 0 {
653 let budget = config!(max_width) - indent - 2;
654 // TODO might need to insert a newline if the generics are really long
657 // Strings for the generics.
658 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
659 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
661 // Extract comments between generics.
662 let lt_spans = lifetimes.iter().map(|l| {
663 let hi = if l.bounds.len() == 0 {
666 l.bounds[l.bounds.len() - 1].span.hi
668 codemap::mk_sp(l.lifetime.span.lo, hi)
670 let ty_spans = tys.iter().map(span_for_ty_param);
671 let comments = self.make_comments_for_list(Vec::new(),
672 lt_spans.chain(ty_spans),
679 // If there are // comments, keep them multi-line.
680 let mut list_tactic = ListTactic::HorizontalVertical;
681 if comments.iter().any(|c| c.contains("//")) {
682 list_tactic = ListTactic::Vertical;
685 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
686 let fmt = ListFormatting {
689 trailing_separator: SeparatorTactic::Never,
694 result.push_str(&write_list(&generics_strs, &fmt));
701 fn rewrite_where_clause(&self,
702 where_clause: &ast::WhereClause,
707 let mut result = String::new();
708 if where_clause.predicates.len() == 0 {
713 result.push_str(&make_indent(indent + 4));
714 result.push_str("where ");
716 let comments = self.make_comments_for_list(Vec::new(),
717 where_clause.predicates.iter(),
720 |pred| span_for_where_pred(pred).lo,
721 |pred| span_for_where_pred(pred).hi,
724 let where_strs: Vec<_> = where_clause.predicates.iter()
725 .map(|p| (self.rewrite_pred(p)))
726 .zip(comments.into_iter())
729 let budget = config!(ideal_width) + config!(leeway) - indent - 10;
730 let fmt = ListFormatting {
731 tactic: ListTactic::Vertical,
733 trailing_separator: SeparatorTactic::Never,
738 result.push_str(&write_list(&where_strs, &fmt));
743 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
745 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
746 ast::FunctionRetTy::NoReturn(_) => "-> !".to_owned(),
747 ast::FunctionRetTy::Return(ref ty) => "-> ".to_owned() + &pprust::ty_to_string(ty),
751 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
752 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
754 pprust::pat_to_string(&arg.pat),
755 pprust::ty_to_string(&arg.ty))
759 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
761 ast::FunctionRetTy::NoReturn(ref span) |
762 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
763 ast::FunctionRetTy::Return(ref ty) => ty.span,
767 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
768 // Note that ty.span is the span for ty.ident, not the whole item.
770 if let Some(ref def) = ty.default {
771 return codemap::mk_sp(lo, def.span.hi);
773 if ty.bounds.len() == 0 {
776 let hi = match ty.bounds[ty.bounds.len() - 1] {
777 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
778 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
780 codemap::mk_sp(lo, hi)
783 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
785 ast::WherePredicate::BoundPredicate(ref p) => p.span,
786 ast::WherePredicate::RegionPredicate(ref p) => p.span,
787 ast::WherePredicate::EqPredicate(ref p) => p.span,