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 use std::cmp::Ordering;
12 use std::borrow::Borrow;
15 use rewrite::{Rewrite, RewriteContext};
16 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
17 use string::{StringFormat, rewrite_string};
18 use utils::{span_after, extra_offset, first_line_width, last_line_width, wrap_str, binary_search};
19 use visitor::FmtVisitor;
20 use config::{StructLitStyle, MultilineStyle};
21 use comment::{FindUncommented, rewrite_comment, contains_comment};
22 use types::rewrite_path;
23 use items::{span_lo_for_arg, span_hi_for_arg};
24 use chains::rewrite_chain;
25 use macros::rewrite_macro;
27 use syntax::{ast, ptr};
28 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
29 use syntax::visit::Visitor;
31 impl Rewrite for ast::Expr {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34 ast::Expr_::ExprVec(ref expr_vec) => {
35 rewrite_array(expr_vec.iter().map(|e| &**e), self.span, context, width, offset)
37 ast::Expr_::ExprLit(ref l) => {
39 ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
40 rewrite_string_lit(context, l.span, width, offset)
43 wrap_str(context.snippet(self.span),
44 context.config.max_width,
50 ast::Expr_::ExprCall(ref callee, ref args) => {
51 let inner_span = mk_sp(callee.span.hi, self.span.hi);
52 rewrite_call(context, &**callee, args, inner_span, width, offset)
54 ast::Expr_::ExprParen(ref subexpr) => {
55 rewrite_paren(context, subexpr, width, offset)
57 ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
58 rewrite_binary_op(context, op, lhs, rhs, width, offset)
60 ast::Expr_::ExprUnary(ref op, ref subexpr) => {
61 rewrite_unary_op(context, op, subexpr, width, offset)
63 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
64 rewrite_struct_lit(context,
67 base.as_ref().map(|e| &**e),
72 ast::Expr_::ExprTup(ref items) => {
73 rewrite_tuple_lit(context, items, self.span, width, offset)
75 ast::Expr_::ExprWhile(ref cond, ref block, label) => {
76 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
78 ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
79 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
81 ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
82 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
84 ast::Expr_::ExprLoop(ref block, label) => {
85 Loop::new_loop(block, label).rewrite(context, width, offset)
87 ast::Expr_::ExprBlock(ref block) => {
88 block.rewrite(context, width, offset)
90 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
91 rewrite_if_else(context,
94 else_block.as_ref().map(|e| &**e),
100 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
101 rewrite_if_else(context,
104 else_block.as_ref().map(|e| &**e),
110 // We reformat it ourselves because rustc gives us a bad span
111 // for ranges, see rust#27162
112 ast::Expr_::ExprRange(ref left, ref right) => {
113 rewrite_range(context,
114 left.as_ref().map(|e| &**e),
115 right.as_ref().map(|e| &**e),
119 ast::Expr_::ExprMatch(ref cond, ref arms, _) => {
120 rewrite_match(context, cond, arms, width, offset)
122 ast::Expr_::ExprPath(ref qself, ref path) => {
123 rewrite_path(context, qself.as_ref(), path, width, offset)
125 ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
126 rewrite_assignment(context, lhs, rhs, None, width, offset)
128 ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
129 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
131 ast::Expr_::ExprAgain(ref opt_ident) => {
132 let id_str = match *opt_ident {
133 Some(ident) => format!(" {}", ident.node),
134 None => String::new(),
136 Some(format!("continue{}", id_str))
138 ast::Expr_::ExprBreak(ref opt_ident) => {
139 let id_str = match *opt_ident {
140 Some(ident) => format!(" {}", ident.node),
141 None => String::new(),
143 Some(format!("break{}", id_str))
145 ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
146 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
148 ast::Expr_::ExprField(..) |
149 ast::Expr_::ExprTupField(..) |
150 ast::Expr_::ExprMethodCall(..) => {
151 rewrite_chain(self, context, width, offset)
153 ast::Expr_::ExprMac(ref mac) => {
154 rewrite_macro(mac, context, width, offset)
156 // We do not format these expressions yet, but they should still
157 // satisfy our width restrictions.
158 _ => wrap_str(context.snippet(self.span), context.config.max_width, width, offset),
163 pub fn rewrite_array<'a, I>(expr_iter: I,
165 context: &RewriteContext,
169 where I: Iterator<Item = &'a ast::Expr>
172 let max_item_width = try_opt!(width.checked_sub(2));
173 let items = itemize_list(context.codemap,
179 // FIXME(#133): itemize_list doesn't support
180 // rewrite failure. This may not be its
181 // responsibility, but that of write_list.
183 item.rewrite(context, max_item_width, offset + 1)
184 .unwrap_or_else(|| context.snippet(item.span))
186 span_after(span, "[", context.codemap),
188 .collect::<Vec<_>>();
190 let tactic = if items.iter().any(|li| li.item.len() > 10 || li.is_multiline()) {
191 ListTactic::HorizontalVertical
196 let fmt = ListFormatting {
199 trailing_separator: SeparatorTactic::Never,
201 h_width: max_item_width,
202 v_width: max_item_width,
203 ends_with_newline: false,
204 config: context.config,
206 let list_str = try_opt!(write_list(&items, &fmt));
208 Some(format!("[{}]", list_str))
211 // This functions is pretty messy because of the wrapping and unwrapping of
212 // expressions into and from blocks. See rust issue #27872.
213 fn rewrite_closure(capture: ast::CaptureClause,
214 fn_decl: &ast::FnDecl,
217 context: &RewriteContext,
221 let mover = if capture == ast::CaptureClause::CaptureByValue {
226 let offset = offset + mover.len();
228 // 4 = "|| {".len(), which is overconservative when the closure consists of
229 // a single expression.
230 let budget = try_opt!(width.checked_sub(4 + mover.len()));
232 let argument_offset = offset + 1;
233 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
234 // 1 = space between arguments and return type.
235 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
237 let arg_items = itemize_list(context.codemap,
238 fn_decl.inputs.iter(),
240 |arg| span_lo_for_arg(arg),
241 |arg| span_hi_for_arg(arg),
243 // FIXME: we should just escalate failure
244 // here, but itemize_list doesn't allow it.
245 arg.rewrite(context, budget, argument_offset)
247 context.snippet(mk_sp(span_lo_for_arg(arg),
248 span_hi_for_arg(arg)))
251 span_after(span, "|", context.codemap),
254 let fmt = ListFormatting {
255 tactic: ListTactic::HorizontalVertical,
257 trailing_separator: SeparatorTactic::Never,
258 indent: argument_offset,
259 h_width: horizontal_budget,
261 ends_with_newline: false,
262 config: context.config,
264 let list_str = try_opt!(write_list(&arg_items.collect::<Vec<_>>(), &fmt));
265 let mut prefix = format!("{}|{}|", mover, list_str);
267 if !ret_str.is_empty() {
268 if prefix.contains('\n') {
270 prefix.push_str(&argument_offset.to_string(context.config));
274 prefix.push_str(&ret_str);
277 // Try to format closure body as a single line expression without braces.
278 if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
279 let (spacer, closer) = if ret_str.is_empty() {
284 let expr = body.expr.as_ref().unwrap();
285 // All closure bodies are blocks in the eyes of the AST, but we may not
286 // want to unwrap them when they only contain a single expression.
287 let inner_expr = match expr.node {
288 ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
290 ast::BlockCheckMode::DefaultBlock => {
291 inner.expr.as_ref().unwrap()
295 let extra_offset = extra_offset(&prefix, offset) + spacer.len();
296 let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
297 let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
299 // Checks if rewrite succeeded and fits on a single line.
300 let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
303 return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
307 // We couldn't format the closure body as a single line expression; fall
308 // back to block formatting.
309 let body_rewrite = body.expr
311 .and_then(|body_expr| {
312 if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
313 Some(inner.rewrite(&context, 2, Indent::empty()))
318 .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
320 Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
323 impl Rewrite for ast::Block {
324 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
325 let user_str = context.snippet(self.span);
326 if user_str == "{}" && width >= 2 {
327 return Some(user_str);
330 let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
331 visitor.block_indent = context.block_indent + context.overflow_indent;
333 let prefix = match self.rules {
334 ast::BlockCheckMode::PushUnsafeBlock(..) |
335 ast::BlockCheckMode::UnsafeBlock(..) => {
336 let snippet = context.snippet(self.span);
337 let open_pos = try_opt!(snippet.find_uncommented("{"));
338 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
340 // Extract comment between unsafe and block start.
341 let trimmed = &snippet[6..open_pos].trim();
343 let prefix = if !trimmed.is_empty() {
344 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
345 let budget = try_opt!(width.checked_sub(9));
346 format!("unsafe {} ",
347 rewrite_comment(trimmed, true, budget, offset + 7, context.config))
352 if is_simple_block(self, context.codemap) && prefix.len() < width {
356 .rewrite(context, width - prefix.len(), offset);
357 if let Some(ref expr_str) = body {
358 let result = format!("{}{{ {} }}", prefix, expr_str);
359 if result.len() <= width && !result.contains('\n') {
367 ast::BlockCheckMode::PopUnsafeBlock(..) |
368 ast::BlockCheckMode::DefaultBlock => {
369 visitor.last_pos = self.span.lo;
375 visitor.visit_block(self);
377 // Push text between last block item and end of block
378 let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
379 visitor.buffer.push_str(&snippet);
381 Some(format!("{}{}", prefix, visitor.buffer))
385 // FIXME(#18): implement pattern formatting
386 impl Rewrite for ast::Pat {
387 fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
388 Some(context.snippet(self.span))
392 // Abstraction over for, while and loop expressions
394 cond: Option<&'a ast::Expr>,
395 block: &'a ast::Block,
396 label: Option<ast::Ident>,
397 pat: Option<&'a ast::Pat>,
404 fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
416 fn new_while(pat: Option<&'a ast::Pat>,
418 block: &'a ast::Block,
419 label: Option<ast::Ident>)
435 fn new_for(pat: &'a ast::Pat,
437 block: &'a ast::Block,
438 label: Option<ast::Ident>)
452 impl<'a> Rewrite for Loop<'a> {
453 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
454 let label_string = rewrite_label(self.label);
456 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
457 let inner_offset = offset + self.keyword.len() + label_string.len();
459 let pat_expr_string = match self.cond {
460 Some(cond) => try_opt!(rewrite_pat_expr(context,
467 None => String::new(),
470 // FIXME: this drops any comment between "loop" and the block.
472 .rewrite(context, width, offset)
473 .map(|result| format!("{}{}{} {}", label_string, self.keyword, pat_expr_string, result))
477 fn rewrite_label(label: Option<ast::Ident>) -> String {
479 Some(ident) => format!("{}: ", ident),
480 None => "".to_owned(),
484 // FIXME: this doesn't play well with line breaks
485 fn rewrite_range(context: &RewriteContext,
486 left: Option<&ast::Expr>,
487 right: Option<&ast::Expr>,
491 let left_string = match left {
494 let max_width = try_opt!(width.checked_sub(2));
495 try_opt!(expr.rewrite(context, max_width, offset))
497 None => String::new(),
500 let right_string = match right {
502 let max_width = try_opt!(width.checked_sub(left_string.len() + 2));
503 try_opt!(expr.rewrite(context, max_width, offset + 2 + left_string.len()))
505 None => String::new(),
508 Some(format!("{}..{}", left_string, right_string))
511 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
512 // treated as an if-let-else expression.
513 fn rewrite_if_else(context: &RewriteContext,
515 if_block: &ast::Block,
516 else_block_opt: Option<&ast::Expr>,
517 pat: Option<&ast::Pat>,
520 allow_single_line: bool)
522 // 3 = "if ", 2 = " {"
523 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
528 try_opt!(width.checked_sub(3 + 2)),
531 // Try to format if-else on single line.
532 if allow_single_line && context.config.single_line_if_else {
533 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
540 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
541 let mut result = format!("if {} {}", pat_expr_string, if_block_string);
543 if let Some(else_block) = else_block_opt {
544 let rewrite = match else_block.node {
545 // If the else expression is another if-else expression, prevent it
546 // from being formatted on a single line.
547 ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
548 rewrite_if_else(context,
551 else_block.as_ref().map(|e| &**e),
557 ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
558 rewrite_if_else(context,
561 else_block.as_ref().map(|e| &**e),
567 _ => else_block.rewrite(context, width, offset),
570 result.push_str(" else ");
571 result.push_str(&&try_opt!(rewrite));
577 fn single_line_if_else(context: &RewriteContext,
579 if_node: &ast::Block,
580 else_block_opt: Option<&ast::Expr>,
583 let else_block = try_opt!(else_block_opt);
584 let fixed_cost = "if { } else { }".len();
586 if let ast::ExprBlock(ref else_node) = else_block.node {
587 if !is_simple_block(if_node, context.codemap) ||
588 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
592 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
593 let if_expr = if_node.expr.as_ref().unwrap();
594 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
596 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
597 let else_expr = else_node.expr.as_ref().unwrap();
598 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
600 // FIXME: this check shouldn't be necessary. Rewrites should either fail
601 // or wrap to a newline when the object does not fit the width.
602 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
604 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
605 return Some(format!("if {} {{ {} }} else {{ {} }}", pat_expr_str, if_str, else_str));
612 // Checks that a block contains no statements, an expression and no comments.
613 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
614 if !block.stmts.is_empty() || block.expr.is_none() {
618 let snippet = codemap.span_to_snippet(block.span).unwrap();
620 !contains_comment(&snippet)
623 fn rewrite_match(context: &RewriteContext,
634 let cond_budget = try_opt!(width.checked_sub(8));
635 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
636 let mut result = format!("match {} {{", cond_str);
638 let nested_context = context.nested_context();
639 let arm_indent = nested_context.block_indent + context.overflow_indent;
640 let arm_indent_str = arm_indent.to_string(context.config);
642 let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
646 for (i, arm) in arms.iter().enumerate() {
647 // Make sure we get the stuff between arms.
648 let missed_str = if i == 0 {
649 context.snippet(mk_sp(open_brace_pos + BytePos(1), arm_start_pos(arm)))
651 context.snippet(mk_sp(arm_end_pos(&arms[i-1]), arm_start_pos(arm)))
653 let missed_str = match missed_str.find_uncommented(",") {
654 Some(n) => &missed_str[n+1..],
655 None => &missed_str[..],
657 // first = first non-whitespace byte index.
658 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
659 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
660 // There were multiple line breaks which got trimmed to nothing
661 // that means there should be some vertical white space. Lets
662 // replace that with just one blank line.
665 let missed_str = missed_str.trim();
666 if !missed_str.is_empty() {
668 result.push_str(&arm_indent_str);
669 result.push_str(missed_str);
672 result.push_str(&arm_indent_str);
674 let arm_str = arm.rewrite(&nested_context,
675 context.config.max_width - arm_indent.width(),
677 if let Some(ref arm_str) = arm_str {
678 result.push_str(arm_str);
680 // We couldn't format the arm, just reproduce the source.
681 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
682 result.push_str(&snippet);
686 // We'll miss any comments etc. between the last arm and the end of the
687 // match expression, but meh.
690 result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
695 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
696 let &ast::Arm { ref attrs, ref pats, .. } = arm;
697 if !attrs.is_empty() {
698 return attrs[0].span.lo
704 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
709 impl Rewrite for ast::Arm {
710 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
711 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
712 let indent_str = offset.to_string(context.config);
714 // FIXME this is all a bit grotty, would be nice to abstract out the
715 // treatment of attributes.
716 let attr_str = if !attrs.is_empty() {
717 // We only use this visitor for the attributes, should we use it for
719 let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
720 attr_visitor.block_indent = context.block_indent;
721 attr_visitor.last_pos = attrs[0].span.lo;
722 if attr_visitor.visit_attrs(attrs) {
723 // Attributes included a skip instruction.
724 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
725 return Some(snippet);
727 attr_visitor.format_missing(pats[0].span.lo);
728 attr_visitor.buffer.to_string()
735 let pat_budget = try_opt!(width.checked_sub(5));
736 let pat_strs = try_opt!(pats.iter()
740 offset.block_indent(context.config))
742 .collect::<Option<Vec<_>>>());
744 let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
746 total_width += (pat_strs.len() - 1) * 3;
748 let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
749 if !vertical && context.config.take_source_hints {
750 // If the patterns were previously stacked, keep them stacked.
751 let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
752 let pat_str = context.snippet(pat_span);
753 vertical = pat_str.find('\n').is_some();
756 let pats_width = if vertical {
757 pat_strs[pat_strs.len() - 1].len()
762 let mut pats_str = String::new();
764 if !pats_str.is_empty() {
766 pats_str.push_str(" |\n");
767 pats_str.push_str(&indent_str);
769 pats_str.push_str(" | ");
772 pats_str.push_str(&p);
775 let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
777 let pats_str = format!("{}{}", pats_str, guard_str);
778 // Where the next text can start.
779 let mut line_start = last_line_width(&pats_str);
780 if pats_str.find('\n').is_none() {
781 line_start += offset.width();
784 let mut line_indent = offset + pats_width;
786 line_indent = line_indent.block_indent(context.config);
789 let comma = if let ast::ExprBlock(_) = body.node {
795 // Let's try and get the arm body on the same line as the condition.
797 if context.config.max_width > line_start + comma.len() + 4 {
798 let budget = context.config.max_width - line_start - comma.len() - 4;
799 if let Some(ref body_str) = body.rewrite(context, budget, line_indent + 4) {
800 if first_line_width(body_str) <= budget {
801 return Some(format!("{}{} => {}{}",
802 attr_str.trim_left(),
810 // We have to push the body to the next line.
811 if comma.is_empty() {
812 // We're trying to fit a block in, but it still failed, give up.
816 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
817 let body_str = try_opt!(body.rewrite(context, body_budget, context.block_indent));
818 Some(format!("{}{} =>\n{}{},",
819 attr_str.trim_left(),
821 offset.block_indent(context.config).to_string(context.config),
826 // The `if ...` guard on a match arm.
827 fn rewrite_guard(context: &RewriteContext,
828 guard: &Option<ptr::P<ast::Expr>>,
831 // The amount of space used up on this line for the pattern in
832 // the arm (excludes offset).
833 pattern_width: usize)
835 if let &Some(ref guard) = guard {
836 // First try to fit the guard string on the same line as the pattern.
837 // 4 = ` if `, 5 = ` => {`
838 let overhead = pattern_width + 4 + 5;
839 if overhead < width {
840 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
841 if let Some(cond_str) = cond_str {
842 return Some(format!(" if {}", cond_str));
846 // Not enough space to put the guard after the pattern, try a newline.
847 let overhead = context.config.tab_spaces + 4 + 5;
848 if overhead < width {
849 let cond_str = guard.rewrite(context,
851 offset.block_indent(context.config));
852 if let Some(cond_str) = cond_str {
853 return Some(format!("\n{}if {}",
854 offset.block_indent(context.config).to_string(context.config),
865 fn rewrite_pat_expr(context: &RewriteContext,
866 pat: Option<&ast::Pat>,
869 // Connecting piece between pattern and expression,
870 // *without* trailing space.
875 let pat_offset = offset + matcher.len();
876 let mut result = match pat {
878 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
879 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
880 format!("{}{}{}", matcher, pat_string, connector)
882 None => String::new(),
885 // Consider only the last line of the pat string.
886 let extra_offset = extra_offset(&result, offset);
888 // The expression may (partionally) fit on the current line.
889 if width > extra_offset + 1 {
890 let spacer = if pat.is_some() {
896 let expr_rewrite = expr.rewrite(context,
897 width - extra_offset - spacer.len(),
898 offset + extra_offset + spacer.len());
900 if let Some(expr_string) = expr_rewrite {
901 result.push_str(spacer);
902 result.push_str(&expr_string);
907 // The expression won't fit on the current line, jump to next.
909 result.push_str(&pat_offset.to_string(context.config));
911 let expr_rewrite = expr.rewrite(context,
912 context.config.max_width - pat_offset.width(),
914 result.push_str(&&try_opt!(expr_rewrite));
919 fn rewrite_string_lit(context: &RewriteContext,
924 if !context.config.format_strings {
925 return Some(context.snippet(span));
928 let fmt = StringFormat {
936 config: context.config,
939 let string_lit = context.snippet(span);
940 let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
942 Some(rewrite_string(str_lit, &fmt))
945 pub fn rewrite_call<R>(context: &RewriteContext,
947 args: &[ptr::P<ast::Expr>],
954 let closure = |callee_max_width| {
955 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
959 let max_width = try_opt!(width.checked_sub(2));
960 binary_search(1, max_width, closure)
963 fn rewrite_call_inner<R>(context: &RewriteContext,
965 max_callee_width: usize,
966 args: &[ptr::P<ast::Expr>],
970 -> Result<String, Ordering>
973 let callee = callee.borrow();
974 // FIXME using byte lens instead of char lens (and probably all over the
976 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
978 if !string.contains('\n') && string.len() > max_callee_width {
979 panic!("{:?} {}", string, max_callee_width);
984 None => return Err(Ordering::Greater),
987 let span_lo = span_after(span, "(", context.codemap);
988 let span = mk_sp(span_lo, span.hi);
990 let extra_offset = extra_offset(&callee_str, offset);
992 let remaining_width = match width.checked_sub(extra_offset + 2) {
994 None => return Err(Ordering::Greater),
996 let offset = offset + extra_offset + 1;
997 let block_indent = if args.len() == 1 {
1002 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1004 let items = itemize_list(context.codemap,
1007 |item| item.span.lo,
1008 |item| item.span.hi,
1009 // Take old span when rewrite fails.
1011 item.rewrite(&inner_context, remaining_width, offset)
1012 .unwrap_or(context.snippet(item.span))
1017 let fmt = ListFormatting::for_fn(remaining_width, offset, context.config);
1018 let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
1020 None => return Err(Ordering::Less),
1023 Ok(format!("{}({})", callee_str, list_str))
1026 fn rewrite_paren(context: &RewriteContext,
1027 subexpr: &ast::Expr,
1031 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1032 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1033 // paren on the same line as the subexpr.
1034 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1035 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1036 subexpr_str.map(|s| format!("({})", s))
1039 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1041 fields: &'a [ast::Field],
1042 base: Option<&'a ast::Expr>,
1047 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1048 assert!(!fields.is_empty() || base.is_some());
1050 enum StructLitField<'a> {
1051 Regular(&'a ast::Field),
1052 Base(&'a ast::Expr),
1056 let path_budget = try_opt!(width.checked_sub(2));
1057 let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1059 // Foo { a: Foo } - indent is +3, width is -5.
1060 let h_budget = try_opt!(width.checked_sub(path_str.len() + 5));
1061 let (indent, v_budget) = match context.config.struct_lit_style {
1062 StructLitStyle::Visual => {
1063 (offset + path_str.len() + 3, h_budget)
1065 StructLitStyle::Block => {
1066 // If we are all on one line, then we'll ignore the indent, and we
1067 // have a smaller budget.
1068 let indent = context.block_indent.block_indent(context.config);
1069 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1074 let field_iter = fields.into_iter()
1075 .map(StructLitField::Regular)
1076 .chain(base.into_iter().map(StructLitField::Base));
1078 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1080 let items = itemize_list(context.codemap,
1085 StructLitField::Regular(ref field) => field.span.lo,
1086 StructLitField::Base(ref expr) => {
1087 let last_field_hi = fields.last()
1089 |field| field.span.hi);
1090 let snippet = context.snippet(mk_sp(last_field_hi,
1092 let pos = snippet.find_uncommented("..").unwrap();
1093 last_field_hi + BytePos(pos as u32)
1099 StructLitField::Regular(ref field) => field.span.hi,
1100 StructLitField::Base(ref expr) => expr.span.hi,
1105 StructLitField::Regular(ref field) => {
1106 rewrite_field(inner_context, &field, h_budget, indent)
1107 .unwrap_or(context.snippet(field.span))
1109 StructLitField::Base(ref expr) => {
1111 expr.rewrite(inner_context, h_budget - 2, indent + 2)
1112 .map(|s| format!("..{}", s))
1113 .unwrap_or(context.snippet(expr.span))
1117 span_after(span, "{", context.codemap),
1120 let fmt = ListFormatting {
1121 tactic: match (context.config.struct_lit_style, fields.len()) {
1122 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1123 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1126 trailing_separator: if base.is_some() {
1127 SeparatorTactic::Never
1129 context.config.struct_lit_trailing_comma
1134 ends_with_newline: false,
1135 config: context.config,
1137 let fields_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1139 let format_on_newline = || {
1140 let inner_indent = context.block_indent
1141 .block_indent(context.config)
1142 .to_string(context.config);
1143 let outer_indent = context.block_indent.to_string(context.config);
1144 Some(format!("{} {{\n{}{}\n{}}}", path_str, inner_indent, fields_str, outer_indent))
1147 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1148 (StructLitStyle::Block, _) if fields_str.contains('\n') => format_on_newline(),
1149 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1150 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1153 // FIXME if context.config.struct_lit_style == Visual, but we run out
1154 // of space, we should fall back to BlockIndent.
1157 fn rewrite_field(context: &RewriteContext,
1162 let name = &field.ident.node.to_string();
1163 let overhead = name.len() + 2;
1164 let expr = field.expr
1165 .rewrite(context, try_opt!(width.checked_sub(overhead)), offset + overhead);
1166 expr.map(|s| format!("{}: {}", name, s))
1169 fn rewrite_tuple_lit(context: &RewriteContext,
1170 items: &[ptr::P<ast::Expr>],
1175 debug!("rewrite_tuple_lit: width: {}, offset: {:?}", width, offset);
1176 let indent = offset + 1;
1177 // In case of length 1, need a trailing comma
1178 if items.len() == 1 {
1180 let budget = try_opt!(width.checked_sub(3));
1181 return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1184 let items = itemize_list(context.codemap,
1187 |item| item.span.lo,
1188 |item| item.span.hi,
1190 let inner_width = context.config.max_width - indent.width() - 1;
1191 item.rewrite(context, inner_width, indent)
1192 .unwrap_or(context.snippet(item.span))
1194 span.lo + BytePos(1), // Remove parens
1195 span.hi - BytePos(1));
1197 let budget = try_opt!(width.checked_sub(2));
1198 let fmt = ListFormatting::for_fn(budget, indent, context.config);
1199 let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1201 Some(format!("({})", list_str))
1204 fn rewrite_binary_op(context: &RewriteContext,
1211 // FIXME: format comments between operands and operator
1213 let operator_str = context.snippet(op.span);
1215 // Get "full width" rhs and see if it fits on the current line. This
1216 // usually works fairly well since it tends to place operands of
1217 // operations with high precendence close together.
1218 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1220 // Second condition is needed in case of line break not caused by a
1221 // shortage of space, but by end-of-line comments, for example.
1222 // Note that this is non-conservative, but its just to see if it's even
1223 // worth trying to put everything on one line.
1224 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1225 // 1 = space between lhs expr and operator
1226 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1228 result.push_str(&operator_str);
1231 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1233 if rhs_result.len() <= remaining_width {
1234 result.push_str(&rhs_result);
1235 return Some(result);
1238 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1239 if rhs_result.len() <= remaining_width {
1240 result.push_str(&rhs_result);
1241 return Some(result);
1247 // We have to use multiple lines.
1249 // Re-evaluate the lhs because we have more space now:
1250 let budget = try_opt!(context.config
1252 .checked_sub(offset.width() + 1 + operator_str.len()));
1253 Some(format!("{} {}\n{}{}",
1254 try_opt!(lhs.rewrite(context, budget, offset)),
1256 offset.to_string(context.config),
1260 fn rewrite_unary_op(context: &RewriteContext,
1266 // For some reason, an UnOp is not spanned like BinOp!
1267 let operator_str = match *op {
1268 ast::UnOp::UnUniq => "box ",
1269 ast::UnOp::UnDeref => "*",
1270 ast::UnOp::UnNot => "!",
1271 ast::UnOp::UnNeg => "-",
1273 let operator_len = operator_str.len();
1275 expr.rewrite(context, try_opt!(width.checked_sub(operator_len)), offset + operator_len)
1276 .map(|r| format!("{}{}", operator_str, r))
1279 fn rewrite_assignment(context: &RewriteContext,
1282 op: Option<&ast::BinOp>,
1286 let operator_str = match op {
1287 Some(op) => context.snippet(op.span),
1288 None => "=".to_owned(),
1291 // 1 = space between lhs and operator.
1292 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1293 let lhs_str = format!("{} {}", try_opt!(lhs.rewrite(context, max_width, offset)), operator_str);
1295 rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1298 // The left hand side must contain everything up to, and including, the
1299 // assignment operator.
1300 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1306 let mut result = lhs.into();
1308 // 1 = space between operator and rhs.
1309 let max_width = try_opt!(width.checked_sub(result.len() + 1));
1310 let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1315 result.push_str(&new_str)
1318 // Expression did not fit on the same line as the identifier. Retry
1319 // on the next line.
1320 let new_offset = offset.block_indent(context.config);
1321 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1323 // FIXME: we probably should related max_width to width instead of config.max_width
1324 // where is the 1 coming from anyway?
1325 let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1326 let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1327 let overflow_context = context.overflow_context(rhs_indent);
1328 let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1330 result.push_str(&&try_opt!(rhs));