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::{min, Ordering};
13 use std::iter::{repeat, ExactSizeIterator};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
19 use {Indent, Shape, Spanned};
20 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23 rewrite_comment, rewrite_missing_comment, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
25 use items::{span_hi_for_arg, span_lo_for_arg};
26 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
27 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
28 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
29 use macros::{rewrite_macro, MacroPosition};
30 use patterns::{can_be_overflowed_pat, TuplePatField};
31 use rewrite::{Rewrite, RewriteContext};
32 use string::{rewrite_string, StringFormat};
33 use types::{can_be_overflowed_type, rewrite_path, PathContext};
34 use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
35 inner_attributes, last_line_extendable, last_line_width, left_most_sub_expr, mk_sp,
36 outer_attributes, paren_overhead, semicolon_for_stmt, stmt_expr,
37 trimmed_last_line_width, wrap_str};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
41 impl Rewrite for ast::Expr {
42 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
43 format_expr(self, ExprType::SubExpression, context, shape)
47 #[derive(Copy, Clone, PartialEq)]
56 context: &RewriteContext,
59 skip_out_of_file_lines_range!(context, expr.span);
61 if contains_skip(&*expr.attrs) {
62 return Some(context.snippet(expr.span()));
65 let expr_rw = match expr.node {
66 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
67 expr_vec.iter().map(|e| &**e),
68 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
73 ast::ExprKind::Lit(ref l) => match l.node {
74 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
75 rewrite_string_lit(context, l.span, shape)
78 context.snippet(expr.span),
79 context.config.max_width(),
83 ast::ExprKind::Call(ref callee, ref args) => {
84 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
85 rewrite_call_with_binary_search(
88 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
93 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
94 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
95 // FIXME: format comments between operands and operator
100 &format!(" {} ", context.snippet(op.span)),
106 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
107 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
111 base.as_ref().map(|e| &**e),
115 ast::ExprKind::Tup(ref items) => rewrite_tuple(
117 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
121 ast::ExprKind::If(..) |
122 ast::ExprKind::IfLet(..) |
123 ast::ExprKind::ForLoop(..) |
124 ast::ExprKind::Loop(..) |
125 ast::ExprKind::While(..) |
126 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
127 .and_then(|control_flow| control_flow.rewrite(context, shape)),
128 ast::ExprKind::Block(ref block) => {
130 ExprType::Statement => {
131 if is_unsafe_block(block) {
132 block.rewrite(context, shape)
133 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
134 // Rewrite block without trying to put it in a single line.
137 let prefix = try_opt!(block_prefix(context, block, shape));
138 rewrite_block_with_visitor(context, &prefix, block, shape)
141 ExprType::SubExpression => block.rewrite(context, shape),
144 ast::ExprKind::Match(ref cond, ref arms) => {
145 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
147 ast::ExprKind::Path(ref qself, ref path) => {
148 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
150 ast::ExprKind::Assign(ref lhs, ref rhs) => {
151 rewrite_assignment(context, lhs, rhs, None, shape)
153 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
154 rewrite_assignment(context, lhs, rhs, Some(op), shape)
156 ast::ExprKind::Continue(ref opt_ident) => {
157 let id_str = match *opt_ident {
158 Some(ident) => format!(" {}", ident.node),
159 None => String::new(),
162 format!("continue{}", id_str),
163 context.config.max_width(),
167 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
168 let id_str = match *opt_ident {
169 Some(ident) => format!(" {}", ident.node),
170 None => String::new(),
173 if let Some(ref expr) = *opt_expr {
174 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
177 format!("break{}", id_str),
178 context.config.max_width(),
183 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
184 rewrite_unary_prefix(context, "yield ", &**expr, shape)
186 wrap_str("yield".to_string(), context.config.max_width(), shape)
188 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
189 rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
191 ast::ExprKind::Try(..) |
192 ast::ExprKind::Field(..) |
193 ast::ExprKind::TupField(..) |
194 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
195 ast::ExprKind::Mac(ref mac) => {
196 // Failure to rewrite a marco should not imply failure to
197 // rewrite the expression.
198 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
200 context.snippet(expr.span),
201 context.config.max_width(),
206 ast::ExprKind::Ret(None) => {
207 wrap_str("return".to_owned(), context.config.max_width(), shape)
209 ast::ExprKind::Ret(Some(ref expr)) => {
210 rewrite_unary_prefix(context, "return ", &**expr, shape)
212 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
213 ast::ExprKind::AddrOf(mutability, ref expr) => {
214 rewrite_expr_addrof(context, mutability, expr, shape)
216 ast::ExprKind::Cast(ref expr, ref ty) => {
217 rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
219 ast::ExprKind::Type(ref expr, ref ty) => {
220 rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
222 ast::ExprKind::Index(ref expr, ref index) => {
223 rewrite_index(&**expr, &**index, context, shape)
225 ast::ExprKind::Repeat(ref expr, ref repeats) => {
226 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
231 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
233 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
234 let delim = match limits {
235 ast::RangeLimits::HalfOpen => "..",
236 ast::RangeLimits::Closed => "...",
239 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
241 ast::ExprKind::Lit(ref lit) => match lit.node {
242 ast::LitKind::FloatUnsuffixed(..) => {
243 context.snippet(lit.span).ends_with('.')
251 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
252 (Some(lhs), Some(rhs)) => {
253 let sp_delim = if context.config.spaces_around_ranges() {
254 format!(" {} ", delim)
255 } else if needs_space_before_range(context, lhs) {
256 format!(" {}", delim)
260 rewrite_pair(&*lhs, &*rhs, "", &sp_delim, "", context, shape)
262 (None, Some(rhs)) => {
263 let sp_delim = if context.config.spaces_around_ranges() {
264 format!("{} ", delim)
268 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
270 (Some(lhs), None) => {
271 let sp_delim = if context.config.spaces_around_ranges() {
272 format!(" {}", delim)
276 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
278 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
281 // We do not format these expressions yet, but they should still
282 // satisfy our width restrictions.
283 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
284 context.snippet(expr.span),
285 context.config.max_width(),
288 ast::ExprKind::Catch(ref block) => {
289 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
293 let budget = shape.width.checked_sub(9).unwrap_or(0);
297 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
304 .and_then(|expr_str| {
305 recover_comment_removed(expr_str, expr.span, context, shape)
307 .and_then(|expr_str| {
308 let attrs = outer_attributes(&expr.attrs);
309 let attrs_str = try_opt!(attrs.rewrite(context, shape));
311 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
314 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
318 pub fn rewrite_pair<LHS, RHS>(
324 context: &RewriteContext,
331 let sep = if infix.ends_with(' ') { " " } else { "" };
332 let infix = infix.trim_right();
333 let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
334 let lhs_shape = Shape {
335 width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
338 let lhs_result = try_opt!(
339 lhs.rewrite(context, lhs_shape)
340 .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
343 // Try to the both lhs and rhs on the same line.
344 let rhs_orig_result = shape
345 .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
346 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
347 if let Some(ref rhs_result) = rhs_orig_result {
348 // If the rhs looks like block expression, we allow it to stay on the same line
349 // with the lhs even if it is multi-lined.
350 let allow_same_line = rhs_result
353 .map(|first_line| first_line.ends_with('{'))
355 if !rhs_result.contains('\n') || allow_same_line {
356 return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
360 // We have to use multiple lines.
361 // Re-evaluate the rhs because we have more space now:
362 let rhs_shape = match context.config.control_style() {
364 try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
367 // Try to calculate the initial constraint on the right hand side.
368 let rhs_overhead = shape.rhs_overhead(context.config);
370 Shape::indented(shape.indent.block_indent(context.config), context.config)
371 .sub_width(rhs_overhead)
375 let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
379 rhs_shape.indent.to_string(context.config),
385 pub fn rewrite_array<'a, I>(
388 context: &RewriteContext,
390 trailing_comma: bool,
393 I: Iterator<Item = &'a ast::Expr>,
395 let bracket_size = if context.config.spaces_within_square_brackets() {
401 let nested_shape = match context.config.array_layout() {
402 IndentStyle::Block => try_opt!(
405 .block_indent(context.config.tab_spaces())
406 .with_max_width(context.config)
409 IndentStyle::Visual => try_opt!(
411 .visual_indent(bracket_size)
412 .sub_width(bracket_size * 2)
416 let items = itemize_list(
420 |item| item.span.lo(),
421 |item| item.span.hi(),
422 |item| item.rewrite(context, nested_shape),
426 ).collect::<Vec<_>>();
428 if items.is_empty() {
429 if context.config.spaces_within_square_brackets() {
430 return Some("[ ]".to_string());
432 return Some("[]".to_string());
436 let has_long_item = items
438 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
440 let mut tactic = match context.config.array_layout() {
441 IndentStyle::Block => {
442 // FIXME wrong shape in one-line case
443 match shape.width.checked_sub(2 * bracket_size) {
446 ListTactic::LimitedHorizontalVertical(context.config.array_width());
447 definitive_tactic(&items, tactic, Separator::Comma, width)
449 None => DefinitiveListTactic::Vertical,
452 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
455 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
460 DefinitiveListTactic::Mixed
463 let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
464 if context.config.array_horizontal_layout_threshold() > 0 &&
465 items.len() > context.config.array_horizontal_layout_threshold()
467 tactic = DefinitiveListTactic::Mixed;
470 let fmt = ListFormatting {
473 trailing_separator: if trailing_comma {
474 SeparatorTactic::Always
475 } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
476 SeparatorTactic::Never
478 SeparatorTactic::Vertical
480 separator_place: SeparatorPlace::Back,
482 ends_with_newline: ends_with_newline,
483 preserve_newline: false,
484 config: context.config,
486 let list_str = try_opt!(write_list(&items, &fmt));
488 let result = if context.config.array_layout() == IndentStyle::Visual ||
489 tactic == DefinitiveListTactic::Horizontal
491 if context.config.spaces_within_square_brackets() && !list_str.is_empty() {
492 format!("[ {} ]", list_str)
494 format!("[{}]", list_str)
499 nested_shape.indent.to_string(context.config),
501 shape.block().indent.to_string(context.config)
508 // Return type is (prefix, extra_offset)
509 fn rewrite_closure_fn_decl(
510 capture: ast::CaptureBy,
511 fn_decl: &ast::FnDecl,
514 context: &RewriteContext,
516 ) -> Option<(String, usize)> {
517 let mover = if capture == ast::CaptureBy::Value {
522 // 4 = "|| {".len(), which is overconservative when the closure consists of
523 // a single expression.
524 let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
527 let argument_offset = nested_shape.indent + 1;
528 let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
529 let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
531 let arg_items = itemize_list(
533 fn_decl.inputs.iter(),
535 |arg| span_lo_for_arg(arg),
536 |arg| span_hi_for_arg(context, arg),
537 |arg| arg.rewrite(context, arg_shape),
538 context.codemap.span_after(span, "|"),
542 let item_vec = arg_items.collect::<Vec<_>>();
543 // 1 = space between arguments and return type.
544 let horizontal_budget = nested_shape
546 .checked_sub(ret_str.len() + 1)
548 let tactic = definitive_tactic(
550 ListTactic::HorizontalVertical,
554 let arg_shape = match tactic {
555 DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
559 let fmt = ListFormatting {
562 trailing_separator: SeparatorTactic::Never,
563 separator_place: SeparatorPlace::Back,
565 ends_with_newline: false,
566 preserve_newline: true,
567 config: context.config,
569 let list_str = try_opt!(write_list(&item_vec, &fmt));
570 let mut prefix = format!("{}|{}|", mover, list_str);
571 // 1 = space between `|...|` and body.
572 let extra_offset = extra_offset(&prefix, shape) + 1;
574 if !ret_str.is_empty() {
575 if prefix.contains('\n') {
577 prefix.push_str(&argument_offset.to_string(context.config));
581 prefix.push_str(&ret_str);
584 Some((prefix, extra_offset))
587 // This functions is pretty messy because of the rules around closures and blocks:
588 // FIXME - the below is probably no longer true in full.
589 // * if there is a return type, then there must be braces,
590 // * given a closure with braces, whether that is parsed to give an inner block
591 // or not depends on if there is a return type and if there are statements
593 // * if the first expression in the body ends with a block (i.e., is a
594 // statement without needing a semi-colon), then adding or removing braces
595 // can change whether it is treated as an expression or statement.
597 capture: ast::CaptureBy,
598 fn_decl: &ast::FnDecl,
601 context: &RewriteContext,
603 ) -> Option<String> {
604 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
612 // 1 = space between `|...|` and body.
613 let body_shape = try_opt!(shape.offset_left(extra_offset));
615 if let ast::ExprKind::Block(ref block) = body.node {
616 // The body of the closure is an empty block.
617 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
618 return Some(format!("{} {{}}", prefix));
621 // Figure out if the block is necessary.
622 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
623 context.inside_macro ||
624 block_contains_comment(block, context.codemap) ||
625 prefix.contains('\n');
627 let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
632 if no_return_type && !needs_block {
633 // lock.stmts.len() == 1
634 if let Some(expr) = stmt_expr(&block.stmts[0]) {
635 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
642 // We need braces, but we might still prefer a one-liner.
643 let stmt = &block.stmts[0];
644 // 4 = braces and spaces.
645 if let Some(body_shape) = body_shape.sub_width(4) {
646 // Checks if rewrite succeeded and fits on a single line.
647 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
648 return Some(format!("{} {{ {} }}", prefix, rewrite));
653 // Either we require a block, or tried without and failed.
654 rewrite_closure_block(block, &prefix, context, body_shape)
656 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
657 // The closure originally had a non-block expression, but we can't fit on
658 // one line, so we'll insert a block.
659 rewrite_closure_with_block(context, body_shape, &prefix, body)
664 // Rewrite closure with a single expression wrapping its body with block.
665 fn rewrite_closure_with_block(
666 context: &RewriteContext,
670 ) -> Option<String> {
671 let block = ast::Block {
674 id: ast::NodeId::new(0),
675 node: ast::StmtKind::Expr(ptr::P(body.clone())),
679 id: ast::NodeId::new(0),
680 rules: ast::BlockCheckMode::Default,
683 rewrite_closure_block(&block, prefix, context, shape)
686 // Rewrite closure with a single expression without wrapping its body with block.
687 fn rewrite_closure_expr(
690 context: &RewriteContext,
692 ) -> Option<String> {
693 let mut rewrite = expr.rewrite(context, shape);
694 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
695 rewrite = and_one_line(rewrite);
697 rewrite = rewrite.and_then(|rw| {
698 if context.config.multiline_closure_forces_block() && rw.contains('\n') {
704 rewrite.map(|rw| format!("{} {}", prefix, rw))
707 // Rewrite closure whose body is block.
708 fn rewrite_closure_block(
711 context: &RewriteContext,
713 ) -> Option<String> {
714 // Start with visual indent, then fall back to block indent if the
716 let block_threshold = context.config.closure_block_indent_threshold();
717 if block_threshold >= 0 {
718 if let Some(block_str) = block.rewrite(context, shape) {
719 if block_str.matches('\n').count() <= block_threshold as usize &&
720 !need_block_indent(&block_str, shape)
722 if let Some(block_str) = block_str.rewrite(context, shape) {
723 return Some(format!("{} {}", prefix, block_str));
729 // The body of the closure is big enough to be block indented, that
730 // means we must re-format.
731 let block_shape = shape.block();
732 let block_str = try_opt!(block.rewrite(context, block_shape));
733 Some(format!("{} {}", prefix, block_str))
736 fn and_one_line(x: Option<String>) -> Option<String> {
737 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
740 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
741 debug!("nop_block_collapse {:?} {}", block_str, budget);
742 block_str.map(|block_str| {
743 if block_str.starts_with('{') && budget >= 2 &&
744 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
753 fn rewrite_empty_block(
754 context: &RewriteContext,
757 ) -> Option<String> {
758 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
760 return Some("{}".to_owned());
763 // If a block contains only a single-line comment, then leave it on one line.
764 let user_str = context.snippet(block.span);
765 let user_str = user_str.trim();
766 if user_str.starts_with('{') && user_str.ends_with('}') {
767 let comment_str = user_str[1..user_str.len() - 1].trim();
768 if block.stmts.is_empty() && !comment_str.contains('\n') &&
769 !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
771 return Some(format!("{{ {} }}", comment_str));
778 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
779 Some(match block.rules {
780 ast::BlockCheckMode::Unsafe(..) => {
781 let snippet = context.snippet(block.span);
782 let open_pos = try_opt!(snippet.find_uncommented("{"));
783 // Extract comment between unsafe and block start.
784 let trimmed = &snippet[6..open_pos].trim();
786 if !trimmed.is_empty() {
787 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
788 let budget = try_opt!(shape.width.checked_sub(9));
791 try_opt!(rewrite_comment(
794 Shape::legacy(budget, shape.indent + 7),
802 ast::BlockCheckMode::Default => String::new(),
806 fn rewrite_single_line_block(
807 context: &RewriteContext,
811 ) -> Option<String> {
812 if is_simple_block(block, context.codemap) {
813 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
814 let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
815 let result = format!("{}{{ {} }}", prefix, expr_str);
816 if result.len() <= shape.width && !result.contains('\n') {
823 fn rewrite_block_with_visitor(
824 context: &RewriteContext,
828 ) -> Option<String> {
829 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
833 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
834 visitor.block_indent = shape.indent;
835 visitor.is_if_else_block = context.is_if_else_block;
837 ast::BlockCheckMode::Unsafe(..) => {
838 let snippet = context.snippet(block.span);
839 let open_pos = try_opt!(snippet.find_uncommented("{"));
840 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
842 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
845 visitor.visit_block(block, None);
846 Some(format!("{}{}", prefix, visitor.buffer))
849 impl Rewrite for ast::Block {
850 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
851 // shape.width is used only for the single line case: either the empty block `{}`,
852 // or an unsafe expression `unsafe { e }`.
853 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
857 let prefix = try_opt!(block_prefix(context, self, shape));
858 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
862 rewrite_block_with_visitor(context, &prefix, self, shape)
866 impl Rewrite for ast::Stmt {
867 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
868 skip_out_of_file_lines_range!(context, self.span());
870 let result = match self.node {
871 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
872 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
873 let suffix = if semicolon_for_stmt(context, self) {
879 let expr_type = match self.node {
880 ast::StmtKind::Expr(_) => ExprType::SubExpression,
881 ast::StmtKind::Semi(_) => ExprType::Statement,
884 let shape = try_opt!(shape.sub_width(suffix.len()));
885 format_expr(ex, expr_type, context, shape).map(|s| s + suffix)
887 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
889 result.and_then(|res| {
890 recover_comment_removed(res, self.span(), context, shape)
895 // Rewrite condition if the given expression has one.
896 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
898 ast::ExprKind::Match(ref cond, _) => {
900 let cond_shape = match context.config.control_style() {
901 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
902 Style::Rfc => try_opt!(shape.offset_left(8)),
904 cond.rewrite(context, cond_shape)
906 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
907 stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
909 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
911 String::from("\n") + &shape.indent.block_only().to_string(context.config);
913 .rewrite_cond(context, shape, &alt_block_sep)
914 .and_then(|rw| Some(rw.0))
919 // Abstraction over control flow expressions
921 struct ControlFlow<'a> {
922 cond: Option<&'a ast::Expr>,
923 block: &'a ast::Block,
924 else_block: Option<&'a ast::Expr>,
925 label: Option<ast::SpannedIdent>,
926 pat: Option<&'a ast::Pat>,
930 allow_single_line: bool,
931 // True if this is an `if` expression in an `else if` :-( hacky
936 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
938 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
942 else_block.as_ref().map(|e| &**e),
943 expr_type == ExprType::SubExpression,
947 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
948 Some(ControlFlow::new_if(
952 else_block.as_ref().map(|e| &**e),
953 expr_type == ExprType::SubExpression,
958 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
959 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
961 ast::ExprKind::Loop(ref block, label) => {
962 Some(ControlFlow::new_loop(block, label, expr.span))
964 ast::ExprKind::While(ref cond, ref block, label) => {
965 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
967 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
968 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
974 impl<'a> ControlFlow<'a> {
977 pat: Option<&'a ast::Pat>,
978 block: &'a ast::Block,
979 else_block: Option<&'a ast::Expr>,
980 allow_single_line: bool,
983 ) -> ControlFlow<'a> {
987 else_block: else_block,
996 allow_single_line: allow_single_line,
997 nested_if: nested_if,
1003 block: &'a ast::Block,
1004 label: Option<ast::SpannedIdent>,
1006 ) -> ControlFlow<'a> {
1016 allow_single_line: false,
1023 pat: Option<&'a ast::Pat>,
1024 cond: &'a ast::Expr,
1025 block: &'a ast::Block,
1026 label: Option<ast::SpannedIdent>,
1028 ) -> ControlFlow<'a> {
1036 matcher: match pat {
1041 allow_single_line: false,
1049 cond: &'a ast::Expr,
1050 block: &'a ast::Block,
1051 label: Option<ast::SpannedIdent>,
1053 ) -> ControlFlow<'a> {
1063 allow_single_line: false,
1069 fn rewrite_single_line(
1072 context: &RewriteContext,
1074 ) -> Option<String> {
1075 assert!(self.allow_single_line);
1076 let else_block = try_opt!(self.else_block);
1077 let fixed_cost = self.keyword.len() + " { } else { }".len();
1079 if let ast::ExprKind::Block(ref else_node) = else_block.node {
1080 if !is_simple_block(self.block, context.codemap) ||
1081 !is_simple_block(else_node, context.codemap) ||
1082 pat_expr_str.contains('\n')
1087 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1088 let expr = &self.block.stmts[0];
1089 let if_str = try_opt!(expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1091 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1092 let else_expr = &else_node.stmts[0];
1094 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1096 if if_str.contains('\n') || else_str.contains('\n') {
1100 let result = format!(
1101 "{} {} {{ {} }} else {{ {} }}",
1108 if result.len() <= width {
1109 return Some(result);
1117 impl<'a> ControlFlow<'a> {
1120 context: &RewriteContext,
1122 alt_block_sep: &str,
1123 ) -> Option<(String, usize)> {
1124 // Do not take the rhs overhead from the upper expressions into account
1125 // when rewriting pattern.
1126 let new_width = context
1129 .checked_sub(shape.used_width())
1131 let fresh_shape = Shape {
1135 let constr_shape = if self.nested_if {
1136 // We are part of an if-elseif-else chain. Our constraints are tightened.
1137 // 7 = "} else " .len()
1138 try_opt!(fresh_shape.offset_left(7))
1143 let label_string = rewrite_label(self.label);
1144 // 1 = space after keyword.
1145 let offset = self.keyword.len() + label_string.len() + 1;
1147 let pat_expr_string = match self.cond {
1149 let cond_shape = match context.config.control_style() {
1150 Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1151 Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1153 try_opt!(rewrite_pat_expr(
1163 None => String::new(),
1166 let brace_overhead =
1167 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1173 let one_line_budget = context
1176 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1178 let force_newline_brace = context.config.control_style() == Style::Rfc &&
1179 (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
1180 !last_line_extendable(&pat_expr_string);
1182 // Try to format if-else on single line.
1183 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1184 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1186 if let Some(cond_str) = trial {
1187 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1188 return Some((cond_str, 0));
1193 let cond_span = if let Some(cond) = self.cond {
1196 mk_sp(self.block.span.lo(), self.block.span.lo())
1199 // `for event in event`
1200 // Do not include label in the span.
1201 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1202 let between_kwd_cond = mk_sp(
1205 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1207 .map_or(cond_span.lo(), |p| if self.matcher.is_empty() {
1210 context.codemap.span_before(self.span, self.matcher.trim())
1214 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1216 let after_cond_comment =
1217 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1219 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1221 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1229 let used_width = if pat_expr_string.contains('\n') {
1230 last_line_width(&pat_expr_string)
1232 // 2 = spaces after keyword and condition.
1233 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1241 between_kwd_cond_comment.as_ref().map_or(
1242 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1250 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1257 impl<'a> Rewrite for ControlFlow<'a> {
1258 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1259 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1262 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1263 let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1264 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1265 if used_width == 0 {
1266 return Some(cond_str);
1269 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1270 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1271 // we should avoid the single line case.
1272 let block_width = if self.else_block.is_some() || self.nested_if {
1277 let block_shape = Shape {
1281 let mut block_context = context.clone();
1282 block_context.is_if_else_block = self.else_block.is_some();
1283 let block_str = try_opt!(rewrite_block_with_visitor(
1290 let mut result = format!("{}{}", cond_str, block_str);
1292 if let Some(else_block) = self.else_block {
1293 let shape = Shape::indented(shape.indent, context.config);
1294 let mut last_in_chain = false;
1295 let rewrite = match else_block.node {
1296 // If the else expression is another if-else expression, prevent it
1297 // from being formatted on a single line.
1298 // Note how we're passing the original shape, as the
1299 // cost of "else" should not cascade.
1300 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1301 ControlFlow::new_if(
1305 next_else_block.as_ref().map(|e| &**e),
1308 mk_sp(else_block.span.lo(), self.span.hi()),
1309 ).rewrite(context, shape)
1311 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1312 ControlFlow::new_if(
1316 next_else_block.as_ref().map(|e| &**e),
1319 mk_sp(else_block.span.lo(), self.span.hi()),
1320 ).rewrite(context, shape)
1323 last_in_chain = true;
1324 // When rewriting a block, the width is only used for single line
1325 // blocks, passing 1 lets us avoid that.
1326 let else_shape = Shape {
1327 width: min(1, shape.width),
1330 format_expr(else_block, ExprType::Statement, context, else_shape)
1334 let between_kwd_else_block = mk_sp(
1335 self.block.span.hi(),
1338 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1340 let between_kwd_else_block_comment =
1341 extract_comment(between_kwd_else_block, context, shape);
1343 let after_else = mk_sp(
1346 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1347 else_block.span.lo(),
1349 let after_else_comment = extract_comment(after_else, context, shape);
1351 let between_sep = match context.config.control_brace_style() {
1352 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1355 ControlBraceStyle::AlwaysSameLine => " ",
1357 let after_sep = match context.config.control_brace_style() {
1358 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1365 between_kwd_else_block_comment
1367 .map_or(between_sep, |s| &**s),
1368 after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1371 result.push_str(&try_opt!(rewrite));
1378 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1380 Some(ident) => format!("{}: ", ident.node),
1381 None => "".to_owned(),
1385 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1386 match rewrite_missing_comment(span, shape, context) {
1387 Some(ref comment) if !comment.is_empty() => Some(format!(
1388 "\n{indent}{}\n{indent}",
1390 indent = shape.indent.to_string(context.config)
1396 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1397 let snippet = codemap.span_to_snippet(block.span).unwrap();
1398 contains_comment(&snippet)
1401 // Checks that a block contains no statements, an expression and no comments.
1402 // FIXME: incorrectly returns false when comment is contained completely within
1404 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1405 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1406 !block_contains_comment(block, codemap))
1409 /// Checks whether a block contains at most one statement or expression, and no comments.
1410 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1411 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1414 /// Checks whether a block contains no statements, expressions, or comments.
1415 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1416 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1419 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1421 ast::StmtKind::Expr(..) => true,
1426 fn is_unsafe_block(block: &ast::Block) -> bool {
1427 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1434 // A simple wrapper type against ast::Arm. Used inside write_list().
1435 struct ArmWrapper<'a> {
1436 pub arm: &'a ast::Arm,
1437 // True if the arm is the last one in match expression. Used to decide on whether we should add
1438 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1442 impl<'a> ArmWrapper<'a> {
1443 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1444 ArmWrapper { arm, is_last }
1448 impl<'a> Rewrite for ArmWrapper<'a> {
1449 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1450 rewrite_match_arm(context, self.arm, shape, self.is_last)
1455 context: &RewriteContext,
1460 attrs: &[ast::Attribute],
1461 ) -> Option<String> {
1462 if arms.is_empty() {
1466 // Do not take the rhs overhead from the upper expressions into account
1467 // when rewriting match condition.
1468 let new_width = try_opt!(context.config.max_width().checked_sub(shape.used_width()));
1469 let cond_shape = Shape {
1474 let cond_shape = match context.config.control_style() {
1475 Style::Legacy => try_opt!(cond_shape.shrink_left(6)),
1476 Style::Rfc => try_opt!(cond_shape.offset_left(6)),
1478 let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1479 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1480 let block_sep = match context.config.control_brace_style() {
1481 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1482 _ if last_line_extendable(&cond_str) => " ",
1484 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1488 let nested_indent_str = shape
1490 .block_indent(context.config)
1491 .to_string(context.config);
1492 // Inner attributes.
1493 let inner_attrs = &inner_attributes(attrs);
1494 let inner_attrs_str = if inner_attrs.is_empty() {
1499 .rewrite(context, shape)
1500 .map(|s| format!("{}{}\n", nested_indent_str, s))
1504 let open_brace_pos = if inner_attrs.is_empty() {
1507 .span_after(mk_sp(cond.span.hi(), arms[0].span().lo()), "{")
1509 inner_attrs[inner_attrs.len() - 1].span().hi()
1512 let arm_indent_str = if context.config.indent_match_arms() {
1515 shape.indent.to_string(context.config)
1519 "match {}{}{{\n{}{}{}\n{}}}",
1524 try_opt!(rewrite_match_arms(
1531 shape.indent.to_string(context.config),
1535 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1536 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1538 } else if config.match_block_trailing_comma() {
1540 } else if let ast::ExprKind::Block(ref block) = body.node {
1541 if let ast::BlockCheckMode::Default = block.rules {
1551 fn rewrite_match_arms(
1552 context: &RewriteContext,
1556 open_brace_pos: BytePos,
1557 ) -> Option<String> {
1558 let arm_shape = if context.config.indent_match_arms() {
1559 shape.block_indent(context.config.tab_spaces())
1561 shape.block_indent(0)
1562 }.with_max_width(context.config);
1564 let arm_len = arms.len();
1565 let is_last_iter = repeat(false)
1566 .take(arm_len.checked_sub(1).unwrap_or(0))
1567 .chain(repeat(true));
1568 let items = itemize_list(
1572 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1574 |arm| arm.arm.span().lo(),
1575 |arm| arm.arm.span().hi(),
1576 |arm| arm.rewrite(context, arm_shape),
1581 let arms_vec: Vec<_> = items.collect();
1582 let fmt = ListFormatting {
1583 tactic: DefinitiveListTactic::Vertical,
1584 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1586 trailing_separator: SeparatorTactic::Never,
1587 separator_place: SeparatorPlace::Back,
1589 ends_with_newline: true,
1590 preserve_newline: true,
1591 config: context.config,
1594 write_list(&arms_vec, &fmt)
1597 fn rewrite_match_arm(
1598 context: &RewriteContext,
1602 ) -> Option<String> {
1603 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1604 if contains_skip(&arm.attrs) {
1605 let (_, body) = flatten_arm_body(context, &arm.body);
1606 // `arm.span()` does not include trailing comma, add it manually.
1607 return Some(format!(
1609 context.snippet(arm.span()),
1610 arm_comma(context.config, body, is_last),
1615 arm.attrs[arm.attrs.len() - 1].span.hi(),
1616 arm.pats[0].span.lo(),
1618 try_opt!(arm.attrs.rewrite(context, shape)),
1621 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1623 let pats_str = try_opt!(
1624 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1625 combine_strs_with_missing_comments(
1640 arm.guard.is_some(),
1645 fn rewrite_match_pattern(
1646 context: &RewriteContext,
1647 pats: &[ptr::P<ast::Pat>],
1648 guard: &Option<ptr::P<ast::Expr>>,
1650 ) -> Option<String> {
1653 let pat_shape = try_opt!(shape.sub_width(5));
1655 let pat_strs = try_opt!(
1657 .map(|p| p.rewrite(context, pat_shape))
1658 .collect::<Option<Vec<_>>>()
1661 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1662 let tactic = definitive_tactic(
1664 ListTactic::HorizontalVertical,
1665 Separator::VerticalBar,
1668 let fmt = ListFormatting {
1671 trailing_separator: SeparatorTactic::Never,
1672 separator_place: context.config.match_pattern_separator_break_point(),
1674 ends_with_newline: false,
1675 preserve_newline: false,
1676 config: context.config,
1678 let pats_str = try_opt!(write_list(&items, &fmt));
1681 let guard_str = try_opt!(rewrite_guard(
1685 trimmed_last_line_width(&pats_str),
1688 Some(format!("{}{}", pats_str, guard_str))
1692 // @extend: true if the arm body can be put next to `=>`
1693 // @body: flattened body, if the body is block with a single expression
1694 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1696 ast::ExprKind::Block(ref block)
1697 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1699 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1701 !context.config.multiline_match_arm_forces_block() &&
1702 expr.can_be_overflowed(context, 1),
1710 !context.config.multiline_match_arm_forces_block() &&
1711 body.can_be_overflowed(context, 1),
1717 fn rewrite_match_body(
1718 context: &RewriteContext,
1719 body: &ptr::P<ast::Expr>,
1724 ) -> Option<String> {
1725 let (extend, body) = flatten_arm_body(context, body);
1727 let comma = arm_comma(context.config, body, is_last);
1728 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1729 let alt_block_sep = alt_block_sep.as_str();
1730 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1731 (true, is_empty_block(block, context.codemap))
1736 let combine_orig_body = |body_str: &str| {
1737 let block_sep = match context.config.control_brace_style() {
1738 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1742 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1745 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1746 let next_line_indent = if is_block {
1749 shape.indent.block_indent(context.config)
1751 let combine_next_line_body = |body_str: &str| {
1753 return Some(format!(
1756 next_line_indent.to_string(context.config),
1761 let indent_str = shape.indent.to_string(context.config);
1762 let nested_indent_str = next_line_indent.to_string(context.config);
1763 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1764 let comma = if context.config.match_block_trailing_comma() {
1769 ("{", format!("\n{}}}{}", indent_str, comma))
1771 ("", String::from(","))
1774 let block_sep = match context.config.control_brace_style() {
1775 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1776 _ if body_prefix.is_empty() => "\n".to_owned(),
1777 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1778 _ => format!(" {}\n", body_prefix),
1779 } + &nested_indent_str;
1790 // Let's try and get the arm body on the same line as the condition.
1792 let orig_body_shape = shape
1793 .offset_left(extra_offset(pats_str, shape) + 4)
1794 .and_then(|shape| shape.sub_width(comma.len()));
1795 let orig_body = if let Some(body_shape) = orig_body_shape {
1796 let rewrite = nop_block_collapse(
1797 format_expr(body, ExprType::Statement, context, body_shape),
1803 if !forbid_same_line &&
1805 (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1807 return combine_orig_body(body_str);
1814 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1816 // Try putting body on the next line and see if it looks better.
1817 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1818 let next_line_body = nop_block_collapse(
1819 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1820 next_line_body_shape.width,
1822 match (orig_body, next_line_body) {
1823 (Some(ref orig_str), Some(ref next_line_str))
1824 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1826 combine_next_line_body(next_line_str)
1828 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1829 combine_orig_body(orig_str)
1831 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1832 combine_next_line_body(next_line_str)
1834 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1835 (None, None) => None,
1836 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1840 // The `if ...` guard on a match arm.
1842 context: &RewriteContext,
1843 guard: &Option<ptr::P<ast::Expr>>,
1845 // The amount of space used up on this line for the pattern in
1846 // the arm (excludes offset).
1847 pattern_width: usize,
1848 ) -> Option<String> {
1849 if let Some(ref guard) = *guard {
1850 // First try to fit the guard string on the same line as the pattern.
1851 // 4 = ` if `, 5 = ` => {`
1852 let cond_shape = shape
1853 .offset_left(pattern_width + 4)
1854 .and_then(|s| s.sub_width(5));
1855 if let Some(cond_shape) = cond_shape {
1856 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1857 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1858 return Some(format!(" if {}", cond_str));
1863 // Not enough space to put the guard after the pattern, try a newline.
1864 // 3 = `if `, 5 = ` => {`
1865 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1867 .and_then(|s| s.sub_width(5));
1868 if let Some(cond_shape) = cond_shape {
1869 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1870 return Some(format!(
1872 cond_shape.indent.to_string(context.config),
1884 fn rewrite_pat_expr(
1885 context: &RewriteContext,
1886 pat: Option<&ast::Pat>,
1889 // Connecting piece between pattern and expression,
1890 // *without* trailing space.
1894 ) -> Option<String> {
1895 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1896 if let Some(pat) = pat {
1897 let matcher = if matcher.is_empty() {
1900 format!("{} ", matcher)
1903 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1904 let pat_string = try_opt!(pat.rewrite(context, pat_shape));
1905 let result = format!("{}{}{}", matcher, pat_string, connector);
1906 return rewrite_assign_rhs(context, result, expr, shape);
1909 let expr_rw = expr.rewrite(context, shape);
1910 // The expression may (partially) fit on the current line.
1911 // We do not allow splitting between `if` and condition.
1912 if keyword == "if" || expr_rw.is_some() {
1916 // The expression won't fit on the current line, jump to next.
1917 let nested_shape = shape
1918 .block_indent(context.config.tab_spaces())
1919 .with_max_width(context.config);
1920 let nested_indent_str = nested_shape.indent.to_string(context.config);
1921 expr.rewrite(context, nested_shape)
1922 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1925 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1926 let string_lit = context.snippet(span);
1928 if !context.config.format_strings() && !context.config.force_format_strings() {
1933 .all(|line| line.ends_with('\\'))
1935 let new_indent = shape.visual_indent(1).indent;
1936 return Some(String::from(
1940 new_indent.to_string(context.config) + line.trim_left()
1942 .collect::<Vec<_>>()
1947 return Some(string_lit);
1951 if !context.config.force_format_strings() &&
1952 !string_requires_rewrite(context, span, &string_lit, shape)
1954 return Some(string_lit);
1957 let fmt = StringFormat {
1964 config: context.config,
1967 // Remove the quote characters.
1968 let str_lit = &string_lit[1..string_lit.len() - 1];
1970 rewrite_string(str_lit, &fmt)
1973 fn string_requires_rewrite(
1974 context: &RewriteContext,
1979 if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
1983 for (i, line) in string.lines().enumerate() {
1985 if line.len() > shape.width {
1988 } else if line.len() > shape.width + shape.indent.width() {
1996 pub fn rewrite_call_with_binary_search<R>(
1997 context: &RewriteContext,
1999 args: &[&ast::Expr],
2006 let force_trailing_comma = if context.inside_macro {
2007 span_ends_with_comma(context, span)
2011 let closure = |callee_max_width| {
2012 // FIXME using byte lens instead of char lens (and probably all over the
2014 let callee_shape = Shape {
2015 width: callee_max_width,
2018 let callee_str = callee
2019 .rewrite(context, callee_shape)
2020 .ok_or(Ordering::Greater)?;
2028 context.config.fn_call_width(),
2029 force_trailing_comma,
2033 binary_search(1, shape.width, closure)
2036 pub fn rewrite_call(
2037 context: &RewriteContext,
2039 args: &[ptr::P<ast::Expr>],
2042 ) -> Option<String> {
2043 let force_trailing_comma = if context.inside_macro {
2044 span_ends_with_comma(context, span)
2051 &args.iter().map(|x| &**x).collect::<Vec<_>>(),
2054 context.config.fn_call_width(),
2055 force_trailing_comma,
2059 pub fn rewrite_call_inner<'a, T>(
2060 context: &RewriteContext,
2065 args_max_width: usize,
2066 force_trailing_comma: bool,
2067 ) -> Result<String, Ordering>
2069 T: Rewrite + Spanned + ToExpr + 'a,
2071 // 2 = `( `, 1 = `(`
2072 let paren_overhead = if context.config.spaces_within_parens() {
2077 let used_width = extra_offset(callee_str, shape);
2078 let one_line_width = shape
2080 .checked_sub(used_width + 2 * paren_overhead)
2081 .ok_or(Ordering::Greater)?;
2083 let nested_shape = shape_from_fn_call_style(
2086 used_width + 2 * paren_overhead,
2087 used_width + paren_overhead,
2088 ).ok_or(Ordering::Greater)?;
2090 let span_lo = context.codemap.span_after(span, "(");
2091 let args_span = mk_sp(span_lo, span.hi());
2093 let (extendable, list_str) = rewrite_call_args(
2100 force_trailing_comma,
2101 ).ok_or(Ordering::Less)?;
2103 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2104 let mut new_context = context.clone();
2105 new_context.use_block = true;
2106 return rewrite_call_inner(
2113 force_trailing_comma,
2117 let args_shape = shape
2118 .sub_width(last_line_width(callee_str))
2119 .ok_or(Ordering::Less)?;
2123 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2127 fn need_block_indent(s: &str, shape: Shape) -> bool {
2128 s.lines().skip(1).any(|s| {
2129 s.find(|c| !char::is_whitespace(c))
2130 .map_or(false, |w| w + 1 < shape.indent.width())
2134 fn rewrite_call_args<'a, T>(
2135 context: &RewriteContext,
2139 one_line_width: usize,
2140 args_max_width: usize,
2141 force_trailing_comma: bool,
2142 ) -> Option<(bool, String)>
2144 T: Rewrite + Spanned + ToExpr + 'a,
2146 let items = itemize_list(
2150 |item| item.span().lo(),
2151 |item| item.span().hi(),
2152 |item| item.rewrite(context, shape),
2157 let mut item_vec: Vec<_> = items.collect();
2159 // Try letting the last argument overflow to the next line with block
2160 // indentation. If its first line fits on one line with the other arguments,
2161 // we format the function arguments horizontally.
2162 let tactic = try_overflow_last_arg(
2171 let fmt = ListFormatting {
2174 trailing_separator: if force_trailing_comma {
2175 SeparatorTactic::Always
2176 } else if context.inside_macro || !context.use_block_indent() {
2177 SeparatorTactic::Never
2179 context.config.trailing_comma()
2181 separator_place: SeparatorPlace::Back,
2183 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2184 preserve_newline: false,
2185 config: context.config,
2188 write_list(&item_vec, &fmt).map(|args_str| {
2189 (tactic != DefinitiveListTactic::Vertical, args_str)
2193 fn try_overflow_last_arg<'a, T>(
2194 context: &RewriteContext,
2195 item_vec: &mut Vec<ListItem>,
2198 one_line_width: usize,
2199 args_max_width: usize,
2200 ) -> DefinitiveListTactic
2202 T: Rewrite + Spanned + ToExpr + 'a,
2204 let overflow_last = can_be_overflowed(context, args);
2206 // Replace the last item with its first line to see if it fits with
2208 let placeholder = if overflow_last {
2209 let mut context = context.clone();
2210 if let Some(expr) = args[args.len() - 1].to_expr() {
2211 if let ast::ExprKind::MethodCall(..) = expr.node {
2212 context.force_one_line_chain = true;
2215 last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
2216 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2222 let mut tactic = definitive_tactic(
2224 ListTactic::LimitedHorizontalVertical(args_max_width),
2229 // Replace the stub with the full overflowing last argument if the rewrite
2230 // succeeded and its first line fits with the other arguments.
2231 match (overflow_last, tactic, placeholder) {
2232 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2233 item_vec[args.len() - 1].item = placeholder;
2235 _ if args.len() >= 1 => {
2236 item_vec[args.len() - 1].item = args.last()
2237 .and_then(|last_arg| last_arg.rewrite(context, shape));
2238 tactic = definitive_tactic(
2240 ListTactic::LimitedHorizontalVertical(args_max_width),
2252 context: &RewriteContext,
2255 args_max_width: usize,
2256 ) -> Option<Shape> {
2257 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2258 acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
2260 let max_width = min(args_max_width, shape.width);
2261 let arg_indent = if context.use_block_indent() {
2262 shape.block().indent.block_unindent(context.config)
2264 shape.block().indent
2267 width: try_opt!(max_width.checked_sub(overhead)),
2273 // Rewriting closure which is placed at the end of the function call's arg.
2274 // Returns `None` if the reformatted closure 'looks bad'.
2275 fn rewrite_last_closure(
2276 context: &RewriteContext,
2279 ) -> Option<String> {
2280 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2281 let body = match body.node {
2282 ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2283 stmt_expr(&block.stmts[0]).unwrap_or(body)
2287 let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2295 // If the closure goes multi line before its body, do not overflow the closure.
2296 if prefix.contains('\n') {
2299 let body_shape = try_opt!(shape.offset_left(extra_offset));
2300 // When overflowing the closure which consists of a single control flow expression,
2301 // force to use block if its condition uses multi line.
2302 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2303 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2305 if is_multi_lined_cond {
2306 return rewrite_closure_with_block(context, body_shape, &prefix, body);
2309 // Seems fine, just format the closure in usual manner.
2310 return expr.rewrite(context, shape);
2315 fn rewrite_last_arg_with_overflow<'a, T>(
2316 context: &RewriteContext,
2318 last_item: &mut ListItem,
2322 T: Rewrite + Spanned + ToExpr + 'a,
2324 let last_arg = args[args.len() - 1];
2325 let rewrite = if let Some(expr) = last_arg.to_expr() {
2327 // When overflowing the closure which consists of a single control flow expression,
2328 // force to use block if its condition uses multi line.
2329 ast::ExprKind::Closure(..) => {
2330 // If the argument consists of multiple closures, we do not overflow
2331 // the last closure.
2332 if args.len() > 1 &&
2336 .filter_map(|arg| arg.to_expr())
2337 .any(|expr| match expr.node {
2338 ast::ExprKind::Closure(..) => true,
2343 rewrite_last_closure(context, expr, shape)
2346 _ => expr.rewrite(context, shape),
2349 last_arg.rewrite(context, shape)
2352 if let Some(rewrite) = rewrite {
2353 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2354 last_item.item = rewrite_first_line;
2361 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2363 T: Rewrite + Spanned + ToExpr + 'a,
2366 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2369 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2371 ast::ExprKind::Match(..) => {
2372 (context.use_block_indent() && args_len == 1) ||
2373 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2375 ast::ExprKind::If(..) |
2376 ast::ExprKind::IfLet(..) |
2377 ast::ExprKind::ForLoop(..) |
2378 ast::ExprKind::Loop(..) |
2379 ast::ExprKind::While(..) |
2380 ast::ExprKind::WhileLet(..) => {
2381 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2383 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2384 context.use_block_indent() ||
2385 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2387 ast::ExprKind::Array(..) |
2388 ast::ExprKind::Call(..) |
2389 ast::ExprKind::Mac(..) |
2390 ast::ExprKind::MethodCall(..) |
2391 ast::ExprKind::Struct(..) |
2392 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2393 ast::ExprKind::AddrOf(_, ref expr) |
2394 ast::ExprKind::Box(ref expr) |
2395 ast::ExprKind::Try(ref expr) |
2396 ast::ExprKind::Unary(_, ref expr) |
2397 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2402 pub fn wrap_args_with_parens(
2403 context: &RewriteContext,
2405 is_extendable: bool,
2407 nested_shape: Shape,
2409 if !context.use_block_indent() ||
2410 (context.inside_macro && !args_str.contains('\n') &&
2411 args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2413 if context.config.spaces_within_parens() && !args_str.is_empty() {
2414 format!("( {} )", args_str)
2416 format!("({})", args_str)
2421 nested_shape.indent.to_string(context.config),
2423 shape.block().indent.to_string(context.config)
2428 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2429 let snippet = context.snippet(span);
2431 .trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2435 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2436 debug!("rewrite_paren, shape: {:?}", shape);
2437 let total_paren_overhead = paren_overhead(context);
2438 let paren_overhead = total_paren_overhead / 2;
2439 let sub_shape = try_opt!(
2441 .offset_left(paren_overhead)
2442 .and_then(|s| s.sub_width(paren_overhead))
2445 let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() {
2446 format!("( {} )", s)
2451 let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2452 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2454 if subexpr_str.contains('\n') ||
2455 first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2457 Some(paren_wrapper(&subexpr_str))
2466 context: &RewriteContext,
2468 ) -> Option<String> {
2469 let expr_str = try_opt!(expr.rewrite(context, shape));
2471 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2477 let offset = last_line_width(&expr_str) + lbr.len();
2478 let rhs_overhead = shape.rhs_overhead(context.config);
2479 let index_shape = if expr_str.contains('\n') {
2480 Shape::legacy(context.config.max_width(), shape.indent)
2481 .offset_left(offset)
2482 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2484 shape.visual_indent(offset).sub_width(offset + rbr.len())
2486 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2488 // Return if index fits in a single line.
2489 match orig_index_rw {
2490 Some(ref index_str) if !index_str.contains('\n') => {
2491 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2496 // Try putting index on the next line and see if it fits in a single line.
2497 let indent = shape.indent.block_indent(context.config);
2498 let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
2499 let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
2500 let new_index_rw = index.rewrite(context, index_shape);
2501 match (orig_index_rw, new_index_rw) {
2502 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2505 indent.to_string(context.config),
2510 (None, Some(ref new_index_str)) => Some(format!(
2513 indent.to_string(context.config),
2518 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2523 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2528 fields.iter().all(|field| !field.is_shorthand)
2531 fn rewrite_struct_lit<'a>(
2532 context: &RewriteContext,
2534 fields: &'a [ast::Field],
2535 base: Option<&'a ast::Expr>,
2538 ) -> Option<String> {
2539 debug!("rewrite_struct_lit: shape {:?}", shape);
2541 enum StructLitField<'a> {
2542 Regular(&'a ast::Field),
2543 Base(&'a ast::Expr),
2547 let path_shape = try_opt!(shape.sub_width(2));
2548 let path_str = try_opt!(rewrite_path(
2556 if fields.is_empty() && base.is_none() {
2557 return Some(format!("{} {{}}", path_str));
2560 // Foo { a: Foo } - indent is +3, width is -5.
2561 let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2563 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2564 let body_lo = context.codemap.span_after(span, "{");
2565 let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
2566 context.config.struct_field_align_threshold() > 0
2568 try_opt!(rewrite_with_alignment(
2572 mk_sp(body_lo, span.hi()),
2576 let field_iter = fields
2578 .map(StructLitField::Regular)
2579 .chain(base.into_iter().map(StructLitField::Base));
2581 let span_lo = |item: &StructLitField| match *item {
2582 StructLitField::Regular(field) => field.span().lo(),
2583 StructLitField::Base(expr) => {
2584 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2585 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2586 let pos = snippet.find_uncommented("..").unwrap();
2587 last_field_hi + BytePos(pos as u32)
2590 let span_hi = |item: &StructLitField| match *item {
2591 StructLitField::Regular(field) => field.span().hi(),
2592 StructLitField::Base(expr) => expr.span.hi(),
2594 let rewrite = |item: &StructLitField| match *item {
2595 StructLitField::Regular(field) => {
2596 // The 1 taken from the v_budget is for the comma.
2597 rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
2599 StructLitField::Base(expr) => {
2601 expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
2602 .map(|s| format!("..{}", s))
2606 let items = itemize_list(
2617 let item_vec = items.collect::<Vec<_>>();
2619 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2620 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2621 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2623 try_opt!(write_list(&item_vec, &fmt))
2626 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2627 Some(format!("{} {{{}}}", path_str, fields_str))
2629 // FIXME if context.config.struct_lit_style() == Visual, but we run out
2630 // of space, we should fall back to BlockIndent.
2633 pub fn wrap_struct_field(
2634 context: &RewriteContext,
2637 nested_shape: Shape,
2638 one_line_width: usize,
2640 if context.config.struct_lit_style() == IndentStyle::Block &&
2641 (fields_str.contains('\n') ||
2642 context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2643 fields_str.len() > one_line_width)
2647 nested_shape.indent.to_string(context.config),
2649 shape.indent.to_string(context.config)
2652 // One liner or visual indent.
2653 format!(" {} ", fields_str)
2657 pub fn struct_lit_field_separator(config: &Config) -> &str {
2659 config.space_before_struct_lit_field_colon(),
2660 config.space_after_struct_lit_field_colon(),
2664 pub fn rewrite_field(
2665 context: &RewriteContext,
2668 prefix_max_width: usize,
2669 ) -> Option<String> {
2670 if contains_skip(&field.attrs) {
2672 context.snippet(field.span()),
2673 context.config.max_width(),
2677 let name = &field.ident.node.to_string();
2678 if field.is_shorthand {
2679 Some(name.to_string())
2681 let mut separator = String::from(struct_lit_field_separator(context.config));
2682 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2683 separator.push(' ');
2685 let overhead = name.len() + separator.len();
2686 let expr_shape = try_opt!(shape.offset_left(overhead));
2687 let expr = field.expr.rewrite(context, expr_shape);
2689 let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
2690 if !attrs_str.is_empty() {
2691 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2695 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2697 let expr_offset = shape.indent.block_indent(context.config);
2700 .rewrite(context, Shape::indented(expr_offset, context.config));
2706 expr_offset.to_string(context.config),
2715 fn shape_from_fn_call_style(
2716 context: &RewriteContext,
2720 ) -> Option<Shape> {
2721 if context.use_block_indent() {
2725 .block_indent(context.config.tab_spaces())
2726 .with_max_width(context.config)
2729 shape.visual_indent(offset).sub_width(overhead)
2733 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2734 context: &RewriteContext,
2740 T: Rewrite + Spanned + ToExpr + 'a,
2742 let mut items = items.iter();
2743 // In case of length 1, need a trailing comma
2744 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2745 if items.len() == 1 {
2747 let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2748 return items.next().unwrap().rewrite(context, nested_shape).map(
2749 |s| if context.config.spaces_within_parens() {
2750 format!("( {}, )", s)
2757 let list_lo = context.codemap.span_after(span, "(");
2758 let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2759 let items = itemize_list(
2763 |item| item.span().lo(),
2764 |item| item.span().hi(),
2765 |item| item.rewrite(context, nested_shape),
2767 span.hi() - BytePos(1),
2770 let item_vec: Vec<_> = items.collect();
2771 let tactic = definitive_tactic(
2773 ListTactic::HorizontalVertical,
2777 let fmt = ListFormatting {
2780 trailing_separator: SeparatorTactic::Never,
2781 separator_place: SeparatorPlace::Back,
2783 ends_with_newline: false,
2784 preserve_newline: false,
2785 config: context.config,
2787 let list_str = try_opt!(write_list(&item_vec, &fmt));
2789 if context.config.spaces_within_parens() && !list_str.is_empty() {
2790 Some(format!("( {} )", list_str))
2792 Some(format!("({})", list_str))
2796 pub fn rewrite_tuple<'a, T>(
2797 context: &RewriteContext,
2803 T: Rewrite + Spanned + ToExpr + 'a,
2805 debug!("rewrite_tuple {:?}", shape);
2806 if context.use_block_indent() {
2807 // We use the same rule as function calls for rewriting tuples.
2808 let force_trailing_comma = if context.inside_macro {
2809 span_ends_with_comma(context, span)
2819 context.config.fn_call_width(),
2820 force_trailing_comma,
2823 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2827 pub fn rewrite_unary_prefix<R: Rewrite>(
2828 context: &RewriteContext,
2832 ) -> Option<String> {
2834 .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2835 .map(|r| format!("{}{}", prefix, r))
2838 // FIXME: this is probably not correct for multi-line Rewrites. we should
2839 // subtract suffix.len() from the last line budget, not the first!
2840 pub fn rewrite_unary_suffix<R: Rewrite>(
2841 context: &RewriteContext,
2845 ) -> Option<String> {
2847 .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2854 fn rewrite_unary_op(
2855 context: &RewriteContext,
2859 ) -> Option<String> {
2860 // For some reason, an UnOp is not spanned like BinOp!
2861 let operator_str = match *op {
2862 ast::UnOp::Deref => "*",
2863 ast::UnOp::Not => "!",
2864 ast::UnOp::Neg => "-",
2866 rewrite_unary_prefix(context, operator_str, expr, shape)
2869 fn rewrite_assignment(
2870 context: &RewriteContext,
2873 op: Option<&ast::BinOp>,
2875 ) -> Option<String> {
2876 let operator_str = match op {
2877 Some(op) => context.snippet(op.span),
2878 None => "=".to_owned(),
2881 // 1 = space between lhs and operator.
2882 let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2883 let lhs_str = format!(
2885 try_opt!(lhs.rewrite(context, lhs_shape)),
2889 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2892 // The left hand side must contain everything up to, and including, the
2893 // assignment operator.
2894 pub fn rewrite_assign_rhs<S: Into<String>>(
2895 context: &RewriteContext,
2899 ) -> Option<String> {
2900 let lhs = lhs.into();
2901 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2902 shape.indent.width()
2906 // 1 = space between operator and rhs.
2907 let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2908 let rhs = try_opt!(choose_rhs(
2912 ex.rewrite(context, orig_shape)
2918 context: &RewriteContext,
2921 orig_rhs: Option<String>,
2922 ) -> Option<String> {
2924 Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
2926 // Expression did not fit on the same line as the identifier.
2927 // Try splitting the line and see if that works better.
2928 let new_shape = try_opt!(
2930 shape.block().indent.block_indent(context.config),
2932 ).sub_width(shape.rhs_overhead(context.config))
2934 let new_rhs = expr.rewrite(context, new_shape);
2935 let new_indent_str = &new_shape.indent.to_string(context.config);
2937 match (orig_rhs, new_rhs) {
2938 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2939 Some(format!("\n{}{}", new_indent_str, new_rhs))
2941 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2942 (None, None) => None,
2943 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2949 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2950 fn count_line_breaks(src: &str) -> usize {
2951 src.chars().filter(|&x| x == '\n').count()
2954 !next_line_rhs.contains('\n') ||
2955 count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2958 fn rewrite_expr_addrof(
2959 context: &RewriteContext,
2960 mutability: ast::Mutability,
2963 ) -> Option<String> {
2964 let operator_str = match mutability {
2965 ast::Mutability::Immutable => "&",
2966 ast::Mutability::Mutable => "&mut ",
2968 rewrite_unary_prefix(context, operator_str, expr, shape)
2972 fn to_expr(&self) -> Option<&ast::Expr>;
2973 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2976 impl ToExpr for ast::Expr {
2977 fn to_expr(&self) -> Option<&ast::Expr> {
2981 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2982 can_be_overflowed_expr(context, self, len)
2986 impl ToExpr for ast::Ty {
2987 fn to_expr(&self) -> Option<&ast::Expr> {
2991 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2992 can_be_overflowed_type(context, self, len)
2996 impl<'a> ToExpr for TuplePatField<'a> {
2997 fn to_expr(&self) -> Option<&ast::Expr> {
3001 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3002 can_be_overflowed_pat(context, self, len)
3006 impl<'a> ToExpr for ast::StructField {
3007 fn to_expr(&self) -> Option<&ast::Expr> {
3011 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {