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 // Try keeping everything on the same line
517 if !result.contains("\n") {
518 // 3 = `() `, space is before ret_string
519 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
523 let one_line_budget = if used_space > self.config.max_width {
526 self.config.max_width - used_space
530 let used_space = indent.width() + result.len() + 2;
531 let max_space = self.config.max_width;
532 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
535 if used_space < max_space {
536 return (one_line_budget,
537 max_space - used_space,
538 indent + result.len() + 1);
542 // Didn't work. we must force vertical layout and put args on a newline.
543 let new_indent = indent.block_indent(self.config);
544 let used_space = new_indent.width() + 2; // account for `(` and `)`
545 let max_space = self.config.max_width;
546 if used_space <= max_space {
547 (0, max_space - used_space, new_indent)
550 // TODO: take evasive action, perhaps kill the indent or something.
551 panic!("in compute_budgets_for_args");
555 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
556 match self.config.fn_brace_style {
557 BraceStyle::AlwaysNextLine => true,
558 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
563 pub fn visit_enum(&mut self,
565 vis: ast::Visibility,
566 enum_def: &ast::EnumDef,
567 generics: &ast::Generics,
569 let header_str = self.format_header("enum ", ident, vis);
570 self.buffer.push_str(&header_str);
572 let enum_snippet = self.snippet(span);
573 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
574 let generics_str = self.format_generics(generics,
577 self.block_indent.block_indent(self.config),
578 codemap::mk_sp(span.lo, body_start))
580 self.buffer.push_str(&generics_str);
582 self.last_pos = body_start;
583 self.block_indent = self.block_indent.block_indent(self.config);
584 for (i, f) in enum_def.variants.iter().enumerate() {
585 let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
588 enum_def.variants[i + 1].span.lo
591 self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
593 self.block_indent = self.block_indent.block_unindent(self.config);
595 self.format_missing_with_indent(span.hi - BytePos(1));
596 self.buffer.push_str("}");
599 // Variant of an enum.
600 fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
601 if self.visit_attrs(&field.node.attrs) {
605 self.format_missing_with_indent(field.span.lo);
607 let result = match field.node.kind {
608 ast::VariantKind::TupleVariantKind(ref types) => {
609 let name = field.node.name.to_string();
610 self.buffer.push_str(&name);
612 let mut result = String::new();
614 if !types.is_empty() {
615 let items = itemize_list(self.codemap,
618 |arg| arg.ty.span.lo,
619 |arg| arg.ty.span.hi,
621 // FIXME silly width, indent
623 .rewrite(&self.get_context(),
628 span_after(field.span, "(", self.codemap),
633 let indent = self.block_indent + field.node.name.to_string().len() + "(".len();
635 let comma_cost = if self.config.enum_trailing_comma {
640 let budget = self.config.max_width - indent.width() - comma_cost - 1; // 1 = )
642 let fmt = ListFormatting {
643 tactic: ListTactic::HorizontalVertical,
645 trailing_separator: SeparatorTactic::Never,
649 ends_with_newline: true,
652 let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
653 Some(list_str) => list_str,
657 result.push_str(&list_str);
661 if let Some(ref expr) = field.node.disr_expr {
662 result.push_str(" = ");
663 let expr_snippet = self.snippet(expr.span);
664 result.push_str(&expr_snippet);
666 // Make sure we do not exceed column limit
667 assert!(self.config.max_width >=
668 name.len() + expr_snippet.len() + " = ,".len(),
669 "Enum variant exceeded column limit");
674 ast::VariantKind::StructVariantKind(ref struct_def) => {
675 // TODO: Should limit the width, as we have a trailing comma
676 let struct_rewrite = self.format_struct("",
678 ast::Visibility::Inherited,
684 match struct_rewrite {
685 Some(struct_str) => struct_str,
690 self.buffer.push_str(&result);
692 if !last_field || self.config.enum_trailing_comma {
693 self.buffer.push_str(",");
696 self.last_pos = field.span.hi + BytePos(1);
699 fn format_struct(&self,
702 vis: ast::Visibility,
703 struct_def: &ast::StructDef,
704 generics: Option<&ast::Generics>,
708 let mut result = String::with_capacity(1024);
710 let header_str = self.format_header(item_name, ident, vis);
711 result.push_str(&header_str);
713 if struct_def.fields.is_empty() {
718 let is_tuple = match struct_def.fields[0].node.kind {
719 ast::StructFieldKind::NamedField(..) => false,
720 ast::StructFieldKind::UnnamedField(..) => true,
723 let (opener, terminator) = if is_tuple {
729 let generics_str = match generics {
731 try_opt!(self.format_generics(g,
734 offset + header_str.len(),
735 codemap::mk_sp(span.lo,
736 struct_def.fields[0].span.lo)))
738 None => opener.to_owned(),
740 result.push_str(&generics_str);
742 let items = itemize_list(self.codemap,
743 struct_def.fields.iter(),
746 // Include attributes and doc comments, if present
747 if !field.node.attrs.is_empty() {
748 field.node.attrs[0].span.lo
753 |field| field.node.ty.span.hi,
754 |field| self.format_field(field),
755 span_after(span, opener.trim(), self.codemap),
758 // 2 terminators and a semicolon
759 let used_budget = offset.width() + header_str.len() + generics_str.len() + 3;
761 // Conservative approximation
762 let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
763 let break_line = !is_tuple || generics_str.contains('\n') ||
764 single_line_cost as usize + used_budget > self.config.max_width;
766 let tactic = if break_line {
767 let indentation = offset.block_indent(self.config).to_string(self.config);
769 result.push_str(&indentation);
773 ListTactic::Horizontal
777 let budget = self.config.max_width - offset.width() + self.config.tab_spaces - 1;
778 let fmt = ListFormatting {
781 trailing_separator: self.config.struct_trailing_comma,
782 indent: offset.block_indent(self.config),
783 h_width: self.config.max_width,
785 ends_with_newline: true,
789 let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
790 result.push_str(&list_str);
794 result.push_str(&offset.to_string(self.config));
797 result.push_str(terminator);
806 pub fn visit_struct(&mut self,
808 vis: ast::Visibility,
809 struct_def: &ast::StructDef,
810 generics: &ast::Generics,
812 let indent = self.block_indent;
813 let result = self.format_struct("struct ",
821 if let Some(rewrite) = result {
822 self.buffer.push_str(&rewrite);
823 self.last_pos = span.hi;
827 fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
828 format!("{}{}{}", format_visibility(vis), item_name, ident)
831 fn format_generics(&self,
832 generics: &ast::Generics,
835 generics_offset: Indent,
838 let mut result = try_opt!(self.rewrite_generics(generics, offset, generics_offset, span));
840 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
841 let where_clause_str = try_opt!(self.rewrite_where_clause(&generics.where_clause,
846 result.push_str(&where_clause_str);
847 result.push_str(&self.block_indent.to_string(self.config));
849 result.push_str(opener.trim());
851 result.push_str(opener);
858 fn format_field(&self, field: &ast::StructField) -> String {
859 if contains_skip(&field.node.attrs) {
860 return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
863 let name = match field.node.kind {
864 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
865 ast::StructFieldKind::UnnamedField(_) => None,
867 let vis = match field.node.kind {
868 ast::StructFieldKind::NamedField(_, vis) |
869 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
871 // FIXME silly width, indent
872 let typ = field.node.ty.rewrite(&self.get_context(), 1000, Indent::empty()).unwrap();
874 let indent = self.block_indent.block_indent(self.config);
875 let mut attr_str = field.node
877 .rewrite(&self.get_context(),
878 self.config.max_width - indent.width(),
881 if !attr_str.is_empty() {
883 attr_str.push_str(&indent.to_string(self.config));
887 Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
888 None => format!("{}{}{}", attr_str, vis, typ),
892 fn rewrite_generics(&self,
893 generics: &ast::Generics,
895 generics_offset: Indent,
898 // FIXME: convert bounds to where clauses where they get too big or if
899 // there is a where clause at all.
900 let lifetimes: &[_] = &generics.lifetimes;
901 let tys: &[_] = &generics.ty_params;
902 if lifetimes.is_empty() && tys.is_empty() {
903 return Some(String::new());
906 let offset = match self.config.generics_indent {
907 BlockIndentStyle::Inherit => offset,
908 BlockIndentStyle::Tabbed => offset.block_indent(self.config),
910 BlockIndentStyle::Visual => generics_offset + 1,
913 let h_budget = self.config.max_width - generics_offset.width() - 2;
914 // TODO: might need to insert a newline if the generics are really long.
916 // Strings for the generics.
917 let context = self.get_context();
918 // FIXME: don't unwrap
919 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
920 let ty_strs = tys.iter()
921 .map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
923 // Extract comments between generics.
924 let lt_spans = lifetimes.iter().map(|l| {
925 let hi = if l.bounds.is_empty() {
928 l.bounds[l.bounds.len() - 1].span.hi
930 codemap::mk_sp(l.lifetime.span.lo, hi)
932 let ty_spans = tys.iter().map(span_for_ty_param);
934 let items = itemize_list(self.codemap,
935 lt_spans.chain(ty_spans),
940 span_after(span, "<", self.codemap),
942 let mut items = items.collect::<Vec<_>>();
944 for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
948 let fmt = ListFormatting::for_item(h_budget, offset, self.config);
949 let list_str = try_opt!(write_list(&items, &fmt));
951 Some(format!("<{}>", list_str))
954 fn rewrite_where_clause(&self,
955 where_clause: &ast::WhereClause,
961 if where_clause.predicates.is_empty() {
962 return Some(String::new());
965 let extra_indent = match self.config.where_indent {
966 BlockIndentStyle::Inherit => Indent::empty(),
967 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces,
971 let context = self.get_context();
973 let offset = match self.config.where_pred_indent {
974 BlockIndentStyle::Inherit => indent + extra_indent,
975 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
976 // 6 = "where ".len()
977 BlockIndentStyle::Visual => indent + extra_indent + 6,
979 // FIXME: if where_pred_indent != Visual, then the budgets below might
980 // be out by a char or two.
982 let budget = self.config.max_width - offset.width();
983 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
984 let items = itemize_list(self.codemap,
985 where_clause.predicates.iter(),
987 |pred| span_for_where_pred(pred).lo,
988 |pred| span_for_where_pred(pred).hi,
989 // FIXME: we should handle failure better
990 // this will be taken care of when write_list
991 // takes Rewrite object: see issue #133
992 |pred| pred.rewrite(&context, budget, offset).unwrap(),
996 let fmt = ListFormatting {
997 tactic: self.config.where_layout,
999 trailing_separator: SeparatorTactic::Never,
1003 ends_with_newline: true,
1004 config: self.config,
1006 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1008 // 9 = " where ".len() + " {".len()
1009 if density == Density::Tall || preds_str.contains('\n') ||
1010 indent.width() + 9 + preds_str.len() > self.config.max_width {
1011 Some(format!("\n{}where {}",
1012 (indent + extra_indent).to_string(self.config),
1015 Some(format!(" where {}", preds_str))
1020 impl Rewrite for ast::FunctionRetTy {
1021 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1023 ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
1024 ast::FunctionRetTy::NoReturn(_) => {
1026 Some("-> !".to_owned())
1031 ast::FunctionRetTy::Return(ref ty) => {
1032 let inner_width = try_opt!(width.checked_sub(3));
1033 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1039 impl Rewrite for ast::Arg {
1040 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1041 if is_named_arg(self) {
1042 if let ast::Ty_::TyInfer = self.ty.node {
1043 wrap_str(pprust::pat_to_string(&self.pat),
1044 context.config.max_width,
1048 let mut result = pprust::pat_to_string(&self.pat);
1049 result.push_str(": ");
1050 let max_width = try_opt!(width.checked_sub(result.len()));
1051 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1052 result.push_str(&ty_str);
1056 self.ty.rewrite(context, width, offset)
1061 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
1062 match explicit_self.node {
1063 ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
1064 let mut_str = format_mutability(m);
1066 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
1067 None => Some(format!("&{}self", mut_str)),
1070 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
1071 Some(format!("self: {}", pprust::ty_to_string(ty)))
1073 ast::ExplicitSelf_::SelfValue(_) => {
1074 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
1076 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
1078 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
1080 format_mutability(mutability)
1082 panic!("there is a bug or change in structure of AST, aborting.");
1086 Some(format!("{}self", mut_str))
1092 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1093 if is_named_arg(arg) {
1100 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1102 ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
1103 _ => arg.ty.span.hi,
1107 fn is_named_arg(arg: &ast::Arg) -> bool {
1108 if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
1109 ident.node != token::special_idents::invalid
1115 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1117 ast::FunctionRetTy::NoReturn(ref span) |
1118 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
1119 ast::FunctionRetTy::Return(ref ty) => ty.span,
1123 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1124 // Note that ty.span is the span for ty.ident, not the whole item.
1125 let lo = ty.span.lo;
1126 if let Some(ref def) = ty.default {
1127 return codemap::mk_sp(lo, def.span.hi);
1129 if ty.bounds.is_empty() {
1132 let hi = match ty.bounds[ty.bounds.len() - 1] {
1133 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1134 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1136 codemap::mk_sp(lo, hi)
1139 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1141 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1142 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1143 ast::WherePredicate::EqPredicate(ref p) => p.span,