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.
14 use utils::{format_mutability, format_visibility, contains_skip, span_after, end_typaram, wrap_str};
15 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
16 use expr::rewrite_assign_rhs;
17 use comment::FindUncommented;
18 use visitor::FmtVisitor;
19 use rewrite::{Rewrite, RewriteContext};
20 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, StructLitStyle};
22 use syntax::{ast, abi};
23 use syntax::codemap::{self, Span, BytePos};
24 use syntax::print::pprust;
25 use syntax::parse::token;
27 impl<'a> FmtVisitor<'a> {
28 pub fn visit_let(&mut self, local: &ast::Local, span: Span) {
29 self.format_missing_with_indent(span.lo);
31 // String that is placed within the assignment pattern and expression.
33 let mut infix = String::new();
35 if let Some(ref ty) = local.ty {
37 let offset = self.block_indent + 2;
38 let width = self.config.max_width - offset.width();
39 let rewrite = ty.rewrite(&self.get_context(), width, offset);
44 infix.push_str(&result);
50 if local.init.is_some() {
57 // New scope so we drop the borrow of self (context) in time to mutably
58 // borrow self to mutate its buffer.
60 let context = self.get_context();
61 let mut result = "let ".to_owned();
62 let pattern_offset = self.block_indent + result.len() + infix.len();
64 let pattern_width = self.config.max_width.checked_sub(pattern_offset.width() + 1);
65 let pattern_width = match pattern_width {
70 match local.pat.rewrite(&context, pattern_width, pattern_offset) {
71 Some(ref pat_string) => result.push_str(pat_string),
75 result.push_str(&infix);
77 if let Some(ref ex) = local.init {
78 let max_width = self.config.max_width.checked_sub(context.block_indent.width() + 1);
79 let max_width = match max_width {
84 // 1 = trailing semicolon;
85 let rhs = rewrite_assign_rhs(&context, result, ex, max_width, context.block_indent);
88 Some(result) => result,
96 self.buffer.push_str(&result);
97 self.buffer.push_str(";");
98 self.last_pos = span.hi;
101 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
102 self.buffer.push_str("extern ");
104 if fm.abi != abi::Abi::C {
105 self.buffer.push_str(&format!("{} ", fm.abi));
108 let snippet = self.snippet(span);
109 let brace_pos = snippet.find_uncommented("{").unwrap() as u32;
111 // FIXME: this skips comments between the extern keyword and the opening
113 self.last_pos = span.lo + BytePos(brace_pos);
114 self.block_indent = self.block_indent.block_indent(self.config);
116 for item in &fm.items {
117 self.format_foreign_item(&*item);
120 self.block_indent = self.block_indent.block_unindent(self.config);
121 self.format_missing_with_indent(span.hi - BytePos(1));
122 self.buffer.push_str("}");
123 self.last_pos = span.hi;
126 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
127 self.format_missing_with_indent(item.span.lo);
128 // Drop semicolon or it will be interpreted as comment.
129 // FIXME: this may be a faulty span from libsyntax.
130 let span = codemap::mk_sp(item.span.lo, item.span.hi - BytePos(1));
133 ast::ForeignItem_::ForeignItemFn(ref fn_decl, ref generics) => {
134 let indent = self.block_indent;
135 let rewrite = self.rewrite_fn_base(indent,
140 ast::Unsafety::Normal,
141 ast::Constness::NotConst,
142 // These are not actually rust functions,
143 // but we format them as such.
145 ast::Visibility::Inherited,
151 self.buffer.push_str(format_visibility(item.vis));
152 self.buffer.push_str(&new_fn);
153 self.buffer.push_str(";");
155 None => self.format_missing(item.span.hi),
158 ast::ForeignItem_::ForeignItemStatic(ref ty, is_mutable) => {
159 // FIXME(#21): we're dropping potential comments in between the
160 // function keywords here.
161 let mut_str = if is_mutable {
166 let prefix = format!("{}static {}{}: ",
167 format_visibility(item.vis),
170 let offset = self.block_indent + prefix.len();
172 let width = self.config.max_width - offset.width() - 1;
173 let rewrite = ty.rewrite(&self.get_context(), width, offset);
177 self.buffer.push_str(&prefix);
178 self.buffer.push_str(&result);
179 self.buffer.push_str(";");
181 None => self.format_missing(item.span.hi),
186 self.last_pos = item.span.hi;
189 pub fn rewrite_fn(&mut self,
193 explicit_self: Option<&ast::ExplicitSelf>,
194 generics: &ast::Generics,
195 unsafety: ast::Unsafety,
196 constness: ast::Constness,
198 vis: ast::Visibility,
201 let mut newline_brace = self.newline_for_brace(&generics.where_clause);
203 let mut result = try_opt!(self.rewrite_fn_base(indent,
215 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
216 newline_brace = false;
219 // Prepare for the function body by possibly adding a newline and
221 // FIXME we'll miss anything between the end of the signature and the
222 // start of the body, but we need more spans from the compiler to solve
226 result.push_str(&indent.to_string(self.config));
234 pub fn rewrite_required_fn(&mut self,
237 sig: &ast::MethodSig,
240 // Drop semicolon or it will be interpreted as comment
241 let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
243 let mut result = try_opt!(self.rewrite_fn_base(indent,
246 Some(&sig.explicit_self),
251 ast::Visibility::Inherited,
255 // Re-attach semicolon
261 fn rewrite_fn_base(&mut self,
265 explicit_self: Option<&ast::ExplicitSelf>,
266 generics: &ast::Generics,
267 unsafety: ast::Unsafety,
268 constness: ast::Constness,
270 vis: ast::Visibility,
274 // FIXME we'll lose any comments in between parts of the function decl, but anyone
275 // who comments there probably deserves what they get.
277 let where_clause = &generics.where_clause;
279 let mut result = String::with_capacity(1024);
281 result.push_str(format_visibility(vis));
283 if let ast::Unsafety::Unsafe = unsafety {
284 result.push_str("unsafe ");
286 if let ast::Constness::Const = constness {
287 result.push_str("const ");
289 if abi != abi::Rust {
290 result.push_str("extern ");
291 result.push_str(&abi.to_string());
296 result.push_str("fn ");
297 result.push_str(&ident.to_string());
300 let generics_indent = indent + result.len();
301 let generics_span = codemap::mk_sp(span.lo, span_for_return(&fd.output).lo);
302 let generics_str = try_opt!(self.rewrite_generics(generics,
306 result.push_str(&generics_str);
308 let context = self.get_context();
309 let ret_str = fd.output
311 self.config.max_width - indent.width(),
316 let (one_line_budget, multi_line_budget, mut arg_indent) =
317 self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
319 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
324 // Check if vertical layout was forced by compute_budget_for_args.
325 if one_line_budget <= 0 {
326 if self.config.fn_args_paren_newline {
328 result.push_str(&arg_indent.to_string(self.config));
329 arg_indent = arg_indent + 1; // extra space for `(`
332 result.push_str("(\n");
333 result.push_str(&arg_indent.to_string(self.config));
335 } else if self.config.fn_args_layout == StructLitStyle::Block {
336 arg_indent = indent.block_indent(self.config);
337 result.push_str("(\n");
338 result.push_str(&arg_indent.to_string(self.config));
343 // A conservative estimation, to goal is to be over all parens in generics
344 let args_start = generics.ty_params
346 .map(|tp| end_typaram(tp))
348 let args_span = codemap::mk_sp(span_after(codemap::mk_sp(args_start, span.hi),
351 span_for_return(&fd.output).lo);
352 let arg_str = try_opt!(self.rewrite_args(&fd.inputs,
359 result.push_str(&arg_str);
360 if self.config.fn_args_layout == StructLitStyle::Block {
366 if !ret_str.is_empty() {
367 // If we've already gone multi-line, or the return type would push
368 // over the max width, then put the return type on a new line.
369 // Unless we are formatting args like a block, in which case there
370 // should always be room for the return type.
371 if (result.contains("\n") ||
372 result.len() + indent.width() + ret_str.len() > self.config.max_width) &&
373 self.config.fn_args_layout != StructLitStyle::Block {
374 let indent = match self.config.fn_return_indent {
375 ReturnIndent::WithWhereClause => indent + 4,
376 // TODO: we might want to check that using the arg indent
377 // doesn't blow our budget, and if it does, then fallback to
378 // the where clause indent.
383 result.push_str(&indent.to_string(self.config));
387 result.push_str(&ret_str);
389 // Comment between return type and the end of the decl.
390 let snippet_lo = fd.output.span().hi;
391 if where_clause.predicates.is_empty() {
392 let snippet_hi = span.hi;
393 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
394 let snippet = snippet.trim();
395 if !snippet.is_empty() {
397 result.push_str(snippet);
400 // FIXME it would be nice to catch comments between the return type
401 // and the where clause, but we don't have a span for the where
406 let where_density = if (self.config.where_density == Density::Compressed &&
407 (!result.contains('\n') ||
408 self.config.fn_args_layout == StructLitStyle::Block)) ||
409 (self.config.fn_args_layout == StructLitStyle::Block &&
410 ret_str.is_empty()) {
417 let where_clause_str = try_opt!(self.rewrite_where_clause(where_clause,
422 result.push_str(&where_clause_str);
427 fn rewrite_args(&self,
429 explicit_self: Option<&ast::ExplicitSelf>,
430 one_line_budget: usize,
431 multi_line_budget: usize,
436 let context = self.get_context();
437 let mut arg_item_strs = try_opt!(args.iter()
439 arg.rewrite(&context, multi_line_budget, indent)
441 .collect::<Option<Vec<_>>>());
443 // Account for sugary self.
444 // FIXME: the comment for the self argument is dropped. This is blocked
445 // on rust issue #27522.
446 let min_args = explicit_self.and_then(|explicit_self| {
447 rewrite_explicit_self(explicit_self, args)
450 arg_item_strs[0] = self_str;
455 // Comments between args.
456 let mut arg_items = Vec::new();
458 arg_items.push(ListItem::from_str(""));
461 // TODO(#21): if there are no args, there might still be a comment, but
462 // without spans for the comment or parens, there is no chance of
463 // getting it right. You also don't get to put a comment on self, unless
465 if args.len() >= min_args {
466 let comment_span_start = if min_args == 2 {
467 span_after(span, ",", self.codemap)
472 let more_items = itemize_list(self.codemap,
473 args[min_args-1..].iter(),
475 |arg| span_lo_for_arg(arg),
476 |arg| arg.ty.span.hi,
481 arg_items.extend(more_items);
484 assert_eq!(arg_item_strs.len(), arg_items.len());
486 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
490 let indent = match self.config.fn_arg_indent {
491 BlockIndentStyle::Inherit => indent,
492 BlockIndentStyle::Tabbed => indent.block_indent(self.config),
493 BlockIndentStyle::Visual => arg_indent,
496 let fmt = ListFormatting {
497 tactic: self.config.fn_args_density.to_list_tactic(),
499 trailing_separator: SeparatorTactic::Never,
501 h_width: one_line_budget,
502 v_width: multi_line_budget,
503 ends_with_newline: false,
507 write_list(&arg_items, &fmt)
510 fn compute_budgets_for_args(&self,
515 -> (usize, usize, Indent) {
516 let mut budgets = None;
518 // Try keeping everything on the same line
519 if !result.contains("\n") {
520 // 3 = `() `, space is before ret_string
521 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
525 let one_line_budget = if used_space > self.config.max_width {
528 self.config.max_width - used_space
532 let used_space = indent.width() + result.len() + 2;
533 let max_space = self.config.ideal_width + self.config.leeway;
534 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
537 if used_space < max_space {
538 budgets = Some((one_line_budget,
539 max_space - used_space,
540 indent + result.len() + 1));
544 // Didn't work. we must force vertical layout and put args on a newline.
545 if let None = budgets {
546 let new_indent = indent.block_indent(self.config);
547 let used_space = new_indent.width() + 2; // account for `(` and `)`
548 let max_space = self.config.ideal_width + self.config.leeway;
549 if used_space > max_space {
551 // TODO: take evasive action, perhaps kill the indent or something.
553 budgets = Some((0, max_space - used_space, new_indent));
560 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
561 match self.config.fn_brace_style {
562 BraceStyle::AlwaysNextLine => true,
563 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
568 pub fn visit_enum(&mut self,
570 vis: ast::Visibility,
571 enum_def: &ast::EnumDef,
572 generics: &ast::Generics,
574 let header_str = self.format_header("enum ", ident, vis);
575 self.buffer.push_str(&header_str);
577 let enum_snippet = self.snippet(span);
578 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
579 let generics_str = self.format_generics(generics,
582 self.block_indent.block_indent(self.config),
583 codemap::mk_sp(span.lo, body_start))
585 self.buffer.push_str(&generics_str);
587 self.last_pos = body_start;
588 self.block_indent = self.block_indent.block_indent(self.config);
589 for (i, f) in enum_def.variants.iter().enumerate() {
590 let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
593 enum_def.variants[i + 1].span.lo
596 self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
598 self.block_indent = self.block_indent.block_unindent(self.config);
600 self.format_missing_with_indent(span.hi - BytePos(1));
601 self.buffer.push_str("}");
604 // Variant of an enum.
605 fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
606 if self.visit_attrs(&field.node.attrs) {
610 self.format_missing_with_indent(field.span.lo);
612 let result = match field.node.kind {
613 ast::VariantKind::TupleVariantKind(ref types) => {
614 let name = field.node.name.to_string();
615 self.buffer.push_str(&name);
617 let mut result = String::new();
619 if !types.is_empty() {
620 let items = itemize_list(self.codemap,
623 |arg| arg.ty.span.lo,
624 |arg| arg.ty.span.hi,
626 // FIXME silly width, indent
628 .rewrite(&self.get_context(),
633 span_after(field.span, "(", self.codemap),
638 let indent = self.block_indent + field.node.name.to_string().len() + "(".len();
640 let comma_cost = if self.config.enum_trailing_comma {
645 let budget = self.config.ideal_width - indent.width() - comma_cost - 1; // 1 = )
647 let fmt = ListFormatting {
648 tactic: ListTactic::HorizontalVertical,
650 trailing_separator: SeparatorTactic::Never,
654 ends_with_newline: true,
657 let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
658 Some(list_str) => list_str,
662 result.push_str(&list_str);
666 if let Some(ref expr) = field.node.disr_expr {
667 result.push_str(" = ");
668 let expr_snippet = self.snippet(expr.span);
669 result.push_str(&expr_snippet);
671 // Make sure we do not exceed column limit
672 assert!(self.config.max_width >=
673 name.len() + expr_snippet.len() + " = ,".len(),
674 "Enum variant exceeded column limit");
679 ast::VariantKind::StructVariantKind(ref struct_def) => {
680 // TODO: Should limit the width, as we have a trailing comma
681 let struct_rewrite = self.format_struct("",
683 ast::Visibility::Inherited,
689 match struct_rewrite {
690 Some(struct_str) => struct_str,
695 self.buffer.push_str(&result);
697 if !last_field || self.config.enum_trailing_comma {
698 self.buffer.push_str(",");
701 self.last_pos = field.span.hi + BytePos(1);
704 fn format_struct(&self,
707 vis: ast::Visibility,
708 struct_def: &ast::StructDef,
709 generics: Option<&ast::Generics>,
713 let mut result = String::with_capacity(1024);
715 let header_str = self.format_header(item_name, ident, vis);
716 result.push_str(&header_str);
718 if struct_def.fields.is_empty() {
723 let is_tuple = match struct_def.fields[0].node.kind {
724 ast::StructFieldKind::NamedField(..) => false,
725 ast::StructFieldKind::UnnamedField(..) => true,
728 let (opener, terminator) = if is_tuple {
734 let generics_str = match generics {
736 try_opt!(self.format_generics(g,
739 offset + header_str.len(),
740 codemap::mk_sp(span.lo,
741 struct_def.fields[0].span.lo)))
743 None => opener.to_owned(),
745 result.push_str(&generics_str);
747 let items = itemize_list(self.codemap,
748 struct_def.fields.iter(),
751 // Include attributes and doc comments, if present
752 if !field.node.attrs.is_empty() {
753 field.node.attrs[0].span.lo
758 |field| field.node.ty.span.hi,
759 |field| self.format_field(field),
760 span_after(span, opener.trim(), self.codemap),
763 // 2 terminators and a semicolon
764 let used_budget = offset.width() + header_str.len() + generics_str.len() + 3;
766 // Conservative approximation
767 let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
768 let break_line = !is_tuple || generics_str.contains('\n') ||
769 single_line_cost as usize + used_budget > self.config.max_width;
771 let tactic = if break_line {
772 let indentation = offset.block_indent(self.config).to_string(self.config);
774 result.push_str(&indentation);
778 ListTactic::Horizontal
782 let budget = self.config.ideal_width - offset.width() + self.config.tab_spaces - 1;
783 let fmt = ListFormatting {
786 trailing_separator: self.config.struct_trailing_comma,
787 indent: offset.block_indent(self.config),
788 h_width: self.config.max_width,
790 ends_with_newline: true,
794 let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
795 result.push_str(&list_str);
799 result.push_str(&offset.to_string(self.config));
802 result.push_str(terminator);
811 pub fn visit_struct(&mut self,
813 vis: ast::Visibility,
814 struct_def: &ast::StructDef,
815 generics: &ast::Generics,
817 let indent = self.block_indent;
818 let result = self.format_struct("struct ",
826 if let Some(rewrite) = result {
827 self.buffer.push_str(&rewrite);
828 self.last_pos = span.hi;
832 fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
833 format!("{}{}{}", format_visibility(vis), item_name, ident)
836 fn format_generics(&self,
837 generics: &ast::Generics,
840 generics_offset: Indent,
843 let mut result = try_opt!(self.rewrite_generics(generics, offset, generics_offset, span));
845 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
846 let where_clause_str = try_opt!(self.rewrite_where_clause(&generics.where_clause,
851 result.push_str(&where_clause_str);
852 result.push_str(&self.block_indent.to_string(self.config));
854 result.push_str(opener.trim());
856 result.push_str(opener);
863 fn format_field(&self, field: &ast::StructField) -> String {
864 if contains_skip(&field.node.attrs) {
865 return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
868 let name = match field.node.kind {
869 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
870 ast::StructFieldKind::UnnamedField(_) => None,
872 let vis = match field.node.kind {
873 ast::StructFieldKind::NamedField(_, vis) |
874 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
876 // FIXME silly width, indent
877 let typ = field.node.ty.rewrite(&self.get_context(), 1000, Indent::empty()).unwrap();
879 let indent = self.block_indent.block_indent(self.config);
880 let mut attr_str = field.node
882 .rewrite(&self.get_context(),
883 self.config.max_width - indent.width(),
886 if !attr_str.is_empty() {
888 attr_str.push_str(&indent.to_string(self.config));
892 Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
893 None => format!("{}{}{}", attr_str, vis, typ),
897 fn rewrite_generics(&self,
898 generics: &ast::Generics,
900 generics_offset: Indent,
903 // FIXME: convert bounds to where clauses where they get too big or if
904 // there is a where clause at all.
905 let lifetimes: &[_] = &generics.lifetimes;
906 let tys: &[_] = &generics.ty_params;
907 if lifetimes.is_empty() && tys.is_empty() {
908 return Some(String::new());
911 let offset = match self.config.generics_indent {
912 BlockIndentStyle::Inherit => offset,
913 BlockIndentStyle::Tabbed => offset.block_indent(self.config),
915 BlockIndentStyle::Visual => generics_offset + 1,
918 let h_budget = self.config.max_width - generics_offset.width() - 2;
919 // TODO: might need to insert a newline if the generics are really long.
921 // Strings for the generics.
922 let context = self.get_context();
923 // FIXME: don't unwrap
924 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
925 let ty_strs = tys.iter()
926 .map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
928 // Extract comments between generics.
929 let lt_spans = lifetimes.iter().map(|l| {
930 let hi = if l.bounds.is_empty() {
933 l.bounds[l.bounds.len() - 1].span.hi
935 codemap::mk_sp(l.lifetime.span.lo, hi)
937 let ty_spans = tys.iter().map(span_for_ty_param);
939 let items = itemize_list(self.codemap,
940 lt_spans.chain(ty_spans),
945 span_after(span, "<", self.codemap),
947 let mut items = items.collect::<Vec<_>>();
949 for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
953 let fmt = ListFormatting::for_item(h_budget, offset, self.config);
954 let list_str = try_opt!(write_list(&items, &fmt));
956 Some(format!("<{}>", list_str))
959 fn rewrite_where_clause(&self,
960 where_clause: &ast::WhereClause,
966 if where_clause.predicates.is_empty() {
967 return Some(String::new());
970 let extra_indent = match self.config.where_indent {
971 BlockIndentStyle::Inherit => Indent::empty(),
972 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual =>
973 Indent::new(config.tab_spaces, 0),
976 let context = self.get_context();
978 let offset = match self.config.where_pred_indent {
979 BlockIndentStyle::Inherit => indent + extra_indent,
980 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
981 // 6 = "where ".len()
982 BlockIndentStyle::Visual => indent + extra_indent + 6,
984 // FIXME: if where_pred_indent != Visual, then the budgets below might
985 // be out by a char or two.
987 let budget = self.config.ideal_width + self.config.leeway - offset.width();
988 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
989 let items = itemize_list(self.codemap,
990 where_clause.predicates.iter(),
992 |pred| span_for_where_pred(pred).lo,
993 |pred| span_for_where_pred(pred).hi,
994 // FIXME: we should handle failure better
995 // this will be taken care of when write_list
996 // takes Rewrite object: see issue #133
997 |pred| pred.rewrite(&context, budget, offset).unwrap(),
1001 let fmt = ListFormatting {
1002 tactic: self.config.where_layout,
1004 trailing_separator: SeparatorTactic::Never,
1008 ends_with_newline: true,
1009 config: self.config,
1011 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1013 // 9 = " where ".len() + " {".len()
1014 if density == Density::Tall || preds_str.contains('\n') ||
1015 indent.width() + 9 + preds_str.len() > self.config.max_width {
1016 Some(format!("\n{}where {}",
1017 (indent + extra_indent).to_string(self.config),
1020 Some(format!(" where {}", preds_str))
1025 impl Rewrite for ast::FunctionRetTy {
1026 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1028 ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
1029 ast::FunctionRetTy::NoReturn(_) => {
1031 Some("-> !".to_owned())
1036 ast::FunctionRetTy::Return(ref ty) => {
1037 let inner_width = try_opt!(width.checked_sub(3));
1038 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1044 impl Rewrite for ast::Arg {
1045 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1046 if is_named_arg(self) {
1047 if let ast::Ty_::TyInfer = self.ty.node {
1048 wrap_str(pprust::pat_to_string(&self.pat),
1049 context.config.max_width,
1053 let mut result = pprust::pat_to_string(&self.pat);
1054 result.push_str(": ");
1055 let max_width = try_opt!(width.checked_sub(result.len()));
1056 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1057 result.push_str(&ty_str);
1061 self.ty.rewrite(context, width, offset)
1066 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
1067 match explicit_self.node {
1068 ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
1069 let mut_str = format_mutability(m);
1071 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
1072 None => Some(format!("&{}self", mut_str)),
1075 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
1076 Some(format!("self: {}", pprust::ty_to_string(ty)))
1078 ast::ExplicitSelf_::SelfValue(_) => {
1079 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
1081 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
1083 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
1085 format_mutability(mutability)
1087 panic!("there is a bug or change in structure of AST, aborting.");
1091 Some(format!("{}self", mut_str))
1097 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1098 if is_named_arg(arg) {
1105 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1107 ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
1108 _ => arg.ty.span.hi,
1112 fn is_named_arg(arg: &ast::Arg) -> bool {
1113 if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
1114 ident.node != token::special_idents::invalid
1120 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1122 ast::FunctionRetTy::NoReturn(ref span) |
1123 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
1124 ast::FunctionRetTy::Return(ref ty) => ty.span,
1128 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1129 // Note that ty.span is the span for ty.ident, not the whole item.
1130 let lo = ty.span.lo;
1131 if let Some(ref def) = ty.default {
1132 return codemap::mk_sp(lo, def.span.hi);
1134 if ty.bounds.is_empty() {
1137 let hi = match ty.bounds[ty.bounds.len() - 1] {
1138 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1139 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1141 codemap::mk_sp(lo, hi)
1144 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1146 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1147 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1148 ast::WherePredicate::EqPredicate(ref p) => p.span,