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.
13 use std::iter::repeat;
16 use syntax::{ast, ptr};
17 use syntax::codemap::{BytePos, CodeMap, Span};
19 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};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, ListFormatting, ListItem, Separator};
27 use macros::{rewrite_macro, MacroArg, MacroPosition};
28 use patterns::{can_be_overflowed_pat, TuplePatField};
29 use rewrite::{Rewrite, RewriteContext};
30 use shape::{Indent, Shape};
32 use string::{rewrite_string, StringFormat};
33 use types::{can_be_overflowed_type, rewrite_path, PathContext};
34 use utils::{colon_spaces, contains_skip, count_newlines, extra_offset, first_line_width,
35 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
36 paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, trimmed_last_line_width,
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()).to_owned());
65 let expr_rw = match expr.node {
66 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
67 &ptr_vec_to_ref_vec(expr_vec),
69 context.snippet_provider.span_after(expr.span, "["),
76 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
77 ast::ExprKind::Call(ref callee, ref args) => {
78 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
79 let callee_str = callee.rewrite(context, shape)?;
80 rewrite_call(context, &callee_str, args, inner_span, shape)
82 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
83 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
84 // FIXME: format comments between operands and operator
88 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
91 context.config.binop_separator(),
94 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
95 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
99 base.as_ref().map(|e| &**e),
103 ast::ExprKind::Tup(ref items) => {
104 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
106 ast::ExprKind::If(..)
107 | ast::ExprKind::IfLet(..)
108 | ast::ExprKind::ForLoop(..)
109 | ast::ExprKind::Loop(..)
110 | ast::ExprKind::While(..)
111 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
112 .and_then(|control_flow| control_flow.rewrite(context, shape)),
113 ast::ExprKind::Block(ref block) => {
115 ExprType::Statement => {
116 if is_unsafe_block(block) {
117 block.rewrite(context, shape)
118 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
119 // Rewrite block without trying to put it in a single line.
122 let prefix = block_prefix(context, block, shape)?;
123 rewrite_block_with_visitor(context, &prefix, block, shape, true)
126 ExprType::SubExpression => block.rewrite(context, shape),
129 ast::ExprKind::Match(ref cond, ref arms) => {
130 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
132 ast::ExprKind::Path(ref qself, ref path) => {
133 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
135 ast::ExprKind::Assign(ref lhs, ref rhs) => {
136 rewrite_assignment(context, lhs, rhs, None, shape)
138 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
139 rewrite_assignment(context, lhs, rhs, Some(op), shape)
141 ast::ExprKind::Continue(ref opt_label) => {
142 let id_str = match *opt_label {
143 Some(label) => format!(" {}", label.ident),
144 None => String::new(),
146 Some(format!("continue{}", id_str))
148 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
149 let id_str = match *opt_label {
150 Some(label) => format!(" {}", label.ident),
151 None => String::new(),
154 if let Some(ref expr) = *opt_expr {
155 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
157 Some(format!("break{}", id_str))
160 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
161 rewrite_unary_prefix(context, "yield ", &**expr, shape)
163 Some("yield".to_string())
165 ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
166 closures::rewrite_closure(
176 ast::ExprKind::Try(..)
177 | ast::ExprKind::Field(..)
178 | ast::ExprKind::TupField(..)
179 | ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
180 ast::ExprKind::Mac(ref mac) => {
181 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
183 context.snippet(expr.span).to_owned(),
184 context.config.max_width(),
189 ast::ExprKind::Ret(None) => Some("return".to_owned()),
190 ast::ExprKind::Ret(Some(ref expr)) => {
191 rewrite_unary_prefix(context, "return ", &**expr, shape)
193 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
194 ast::ExprKind::AddrOf(mutability, ref expr) => {
195 rewrite_expr_addrof(context, mutability, expr, shape)
197 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
200 PairParts::new("", " as ", ""),
203 SeparatorPlace::Front,
205 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
208 PairParts::new("", ": ", ""),
211 SeparatorPlace::Back,
213 ast::ExprKind::Index(ref expr, ref index) => {
214 rewrite_index(&**expr, &**index, context, shape)
216 ast::ExprKind::Repeat(ref expr, ref repeats) => {
217 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
225 PairParts::new(lbr, "; ", rbr),
228 SeparatorPlace::Back,
231 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
232 let delim = match limits {
233 ast::RangeLimits::HalfOpen => "..",
234 ast::RangeLimits::Closed => "..=",
237 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
239 ast::ExprKind::Lit(ref lit) => match lit.node {
240 ast::LitKind::FloatUnsuffixed(..) => {
241 context.snippet(lit.span).ends_with('.')
249 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
250 (Some(lhs), Some(rhs)) => {
251 let sp_delim = if context.config.spaces_around_ranges() {
252 format!(" {} ", delim)
253 } else if needs_space_before_range(context, lhs) {
254 format!(" {}", delim)
261 PairParts::new("", &sp_delim, ""),
264 context.config.binop_separator(),
267 (None, Some(rhs)) => {
268 let sp_delim = if context.config.spaces_around_ranges() {
269 format!("{} ", delim)
273 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
275 (Some(lhs), None) => {
276 let sp_delim = if context.config.spaces_around_ranges() {
277 format!(" {}", delim)
281 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
283 (None, None) => Some(delim.to_owned()),
286 // We do not format these expressions yet, but they should still
287 // satisfy our width restrictions.
288 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
289 Some(context.snippet(expr.span).to_owned())
291 ast::ExprKind::Catch(ref block) => {
292 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
296 let budget = shape.width.checked_sub(9).unwrap_or(0);
300 block.rewrite(context, Shape::legacy(budget, shape.indent))?
307 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
308 .and_then(|expr_str| {
309 let attrs = outer_attributes(&expr.attrs);
310 let attrs_str = attrs.rewrite(context, shape)?;
312 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
315 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
319 #[derive(new, Clone, Copy)]
320 pub struct PairParts<'a> {
326 pub fn rewrite_pair<LHS, RHS>(
330 context: &RewriteContext,
332 separator_place: SeparatorPlace,
338 let lhs_overhead = match separator_place {
339 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
340 SeparatorPlace::Front => shape.used_width(),
342 let lhs_shape = Shape {
343 width: context.budget(lhs_overhead),
346 let lhs_result = lhs.rewrite(context, lhs_shape)
347 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
349 // Try to the both lhs and rhs on the same line.
350 let rhs_orig_result = shape
351 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
352 .and_then(|s| s.sub_width(pp.suffix.len()))
353 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
354 if let Some(ref rhs_result) = rhs_orig_result {
355 // If the rhs looks like block expression, we allow it to stay on the same line
356 // with the lhs even if it is multi-lined.
357 let allow_same_line = rhs_result
360 .map(|first_line| first_line.ends_with('{'))
362 if !rhs_result.contains('\n') || allow_same_line {
363 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
364 + first_line_width(rhs_result) + pp.suffix.len();
365 if one_line_width <= shape.width {
368 lhs_result, pp.infix, rhs_result, pp.suffix
374 // We have to use multiple lines.
375 // Re-evaluate the rhs because we have more space now:
376 let mut rhs_shape = match context.config.indent_style() {
377 IndentStyle::Visual => shape
378 .sub_width(pp.suffix.len() + pp.prefix.len())?
379 .visual_indent(pp.prefix.len()),
380 IndentStyle::Block => {
381 // Try to calculate the initial constraint on the right hand side.
382 let rhs_overhead = shape.rhs_overhead(context.config);
383 Shape::indented(shape.indent.block_indent(context.config), context.config)
384 .sub_width(rhs_overhead)?
387 let infix = match separator_place {
388 SeparatorPlace::Back => pp.infix.trim_right(),
389 SeparatorPlace::Front => pp.infix.trim_left(),
391 if separator_place == SeparatorPlace::Front {
392 rhs_shape = rhs_shape.offset_left(infix.len())?;
394 let rhs_result = rhs.rewrite(context, rhs_shape)?;
395 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
396 let infix_with_sep = match separator_place {
397 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
398 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
402 lhs_result, infix_with_sep, rhs_result, pp.suffix
406 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
409 context: &RewriteContext,
411 trailing_comma: bool,
412 ) -> Option<String> {
413 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
419 let nested_shape = match context.config.indent_style() {
420 IndentStyle::Block => shape
422 .block_indent(context.config.tab_spaces())
423 .with_max_width(context.config)
425 IndentStyle::Visual => shape
426 .visual_indent(bracket_size)
427 .sub_width(bracket_size * 2)?,
430 let items = itemize_list(
431 context.snippet_provider,
435 |item| item.span().lo(),
436 |item| item.span().hi(),
437 |item| item.rewrite(context, nested_shape),
441 ).collect::<Vec<_>>();
443 if items.is_empty() {
444 if context.config.spaces_within_parens_and_brackets() {
445 return Some("[ ]".to_string());
447 return Some("[]".to_string());
451 let tactic = array_tactic(context, shape, nested_shape, exprs, &items, bracket_size);
452 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
454 let fmt = ListFormatting {
457 trailing_separator: if trailing_comma {
458 SeparatorTactic::Always
459 } else if context.inside_macro && !exprs.is_empty() {
460 let ends_with_bracket = context.snippet(span).ends_with(']');
461 let bracket_offset = if ends_with_bracket { 1 } else { 0 };
462 let snippet = context.snippet(mk_sp(span.lo(), span.hi() - BytePos(bracket_offset)));
463 let last_char_index = snippet.rfind(|c: char| !c.is_whitespace())?;
464 if &snippet[last_char_index..last_char_index + 1] == "," {
465 SeparatorTactic::Always
467 SeparatorTactic::Never
469 } else if context.config.indent_style() == IndentStyle::Visual {
470 SeparatorTactic::Never
472 SeparatorTactic::Vertical
474 separator_place: SeparatorPlace::Back,
477 preserve_newline: false,
478 config: context.config,
480 let list_str = write_list(&items, &fmt)?;
482 let result = if context.config.indent_style() == IndentStyle::Visual
483 || tactic == DefinitiveListTactic::Horizontal
485 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
486 format!("[ {} ]", list_str)
488 format!("[{}]", list_str)
493 nested_shape.indent.to_string_with_newline(context.config),
495 shape.block().indent.to_string_with_newline(context.config)
502 fn array_tactic<T: Rewrite + Spanned + ToExpr>(
503 context: &RewriteContext,
509 ) -> DefinitiveListTactic {
510 let has_long_item = items
512 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
514 match context.config.indent_style() {
515 IndentStyle::Block => {
516 let tactic = match shape.width.checked_sub(2 * bracket_size) {
518 let tactic = ListTactic::LimitedHorizontalVertical(
519 context.config.width_heuristics().array_width,
521 definitive_tactic(items, tactic, Separator::Comma, width)
523 None => DefinitiveListTactic::Vertical,
525 if tactic == DefinitiveListTactic::Vertical && !has_long_item
526 && is_every_args_simple(exprs)
528 DefinitiveListTactic::Mixed
533 IndentStyle::Visual => {
534 if has_long_item || items.iter().any(ListItem::is_multiline) {
537 ListTactic::LimitedHorizontalVertical(
538 context.config.width_heuristics().array_width,
544 DefinitiveListTactic::Mixed
550 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
551 debug!("nop_block_collapse {:?} {}", block_str, budget);
552 block_str.map(|block_str| {
553 if block_str.starts_with('{') && budget >= 2
554 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
563 fn rewrite_empty_block(
564 context: &RewriteContext,
567 ) -> Option<String> {
568 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
570 return Some("{}".to_owned());
573 // If a block contains only a single-line comment, then leave it on one line.
574 let user_str = context.snippet(block.span);
575 let user_str = user_str.trim();
576 if user_str.starts_with('{') && user_str.ends_with('}') {
577 let comment_str = user_str[1..user_str.len() - 1].trim();
578 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
579 && comment_str.len() + 4 <= shape.width
581 return Some(format!("{{ {} }}", comment_str));
588 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
589 Some(match block.rules {
590 ast::BlockCheckMode::Unsafe(..) => {
591 let snippet = context.snippet(block.span);
592 let open_pos = snippet.find_uncommented("{")?;
593 // Extract comment between unsafe and block start.
594 let trimmed = &snippet[6..open_pos].trim();
596 if !trimmed.is_empty() {
597 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
598 let budget = shape.width.checked_sub(9)?;
604 Shape::legacy(budget, shape.indent + 7),
612 ast::BlockCheckMode::Default => String::new(),
616 fn rewrite_single_line_block(
617 context: &RewriteContext,
621 ) -> Option<String> {
622 if is_simple_block(block, context.codemap) {
623 let expr_shape = shape.offset_left(last_line_width(prefix))?;
624 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
625 let result = format!("{}{{ {} }}", prefix, expr_str);
626 if result.len() <= shape.width && !result.contains('\n') {
633 pub fn rewrite_block_with_visitor(
634 context: &RewriteContext,
639 ) -> Option<String> {
640 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
644 let mut visitor = FmtVisitor::from_context(context);
645 visitor.block_indent = shape.indent;
646 visitor.is_if_else_block = context.is_if_else_block;
648 ast::BlockCheckMode::Unsafe(..) => {
649 let snippet = context.snippet(block.span);
650 let open_pos = snippet.find_uncommented("{")?;
651 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
653 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
656 visitor.visit_block(block, None, has_braces);
657 Some(format!("{}{}", prefix, visitor.buffer))
660 impl Rewrite for ast::Block {
661 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
662 // shape.width is used only for the single line case: either the empty block `{}`,
663 // or an unsafe expression `unsafe { e }`.
664 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
668 let prefix = block_prefix(context, self, shape)?;
670 let result = rewrite_block_with_visitor(context, &prefix, self, shape, true);
671 if let Some(ref result_str) = result {
672 if result_str.lines().count() <= 3 {
673 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
683 impl Rewrite for ast::Stmt {
684 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
685 skip_out_of_file_lines_range!(context, self.span());
687 let result = match self.node {
688 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
689 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
690 let suffix = if semicolon_for_stmt(context, self) {
696 let shape = shape.sub_width(suffix.len())?;
697 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
699 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
701 result.and_then(|res| recover_comment_removed(res, self.span(), context))
705 // Rewrite condition if the given expression has one.
706 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
708 ast::ExprKind::Match(ref cond, _) => {
710 let cond_shape = match context.config.indent_style() {
711 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
712 IndentStyle::Block => shape.offset_left(8)?,
714 cond.rewrite(context, cond_shape)
716 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
718 String::from("\n") + &shape.indent.block_only().to_string(context.config);
720 .rewrite_cond(context, shape, &alt_block_sep)
721 .and_then(|rw| Some(rw.0))
726 // Abstraction over control flow expressions
728 struct ControlFlow<'a> {
729 cond: Option<&'a ast::Expr>,
730 block: &'a ast::Block,
731 else_block: Option<&'a ast::Expr>,
732 label: Option<ast::Label>,
733 pat: Option<&'a ast::Pat>,
737 allow_single_line: bool,
738 // True if this is an `if` expression in an `else if` :-( hacky
743 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
745 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
749 else_block.as_ref().map(|e| &**e),
750 expr_type == ExprType::SubExpression,
754 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
755 Some(ControlFlow::new_if(
759 else_block.as_ref().map(|e| &**e),
760 expr_type == ExprType::SubExpression,
765 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
766 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
768 ast::ExprKind::Loop(ref block, label) => {
769 Some(ControlFlow::new_loop(block, label, expr.span))
771 ast::ExprKind::While(ref cond, ref block, label) => {
772 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
774 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
775 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
781 impl<'a> ControlFlow<'a> {
784 pat: Option<&'a ast::Pat>,
785 block: &'a ast::Block,
786 else_block: Option<&'a ast::Expr>,
787 allow_single_line: bool,
790 ) -> ControlFlow<'a> {
809 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
819 allow_single_line: false,
826 pat: Option<&'a ast::Pat>,
828 block: &'a ast::Block,
829 label: Option<ast::Label>,
831 ) -> ControlFlow<'a> {
844 allow_single_line: false,
853 block: &'a ast::Block,
854 label: Option<ast::Label>,
856 ) -> ControlFlow<'a> {
866 allow_single_line: false,
872 fn rewrite_single_line(
875 context: &RewriteContext,
877 ) -> Option<String> {
878 assert!(self.allow_single_line);
879 let else_block = self.else_block?;
880 let fixed_cost = self.keyword.len() + " { } else { }".len();
882 if let ast::ExprKind::Block(ref else_node) = else_block.node {
883 if !is_simple_block(self.block, context.codemap)
884 || !is_simple_block(else_node, context.codemap)
885 || pat_expr_str.contains('\n')
890 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
891 let expr = &self.block.stmts[0];
892 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
894 let new_width = new_width.checked_sub(if_str.len())?;
895 let else_expr = &else_node.stmts[0];
896 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
898 if if_str.contains('\n') || else_str.contains('\n') {
902 let result = format!(
903 "{} {} {{ {} }} else {{ {} }}",
904 self.keyword, pat_expr_str, if_str, else_str
907 if result.len() <= width {
916 impl<'a> ControlFlow<'a> {
919 context: &RewriteContext,
922 ) -> Option<(String, usize)> {
923 // Do not take the rhs overhead from the upper expressions into account
924 // when rewriting pattern.
925 let new_width = context
928 .checked_sub(shape.used_width())
930 let fresh_shape = Shape {
934 let constr_shape = if self.nested_if {
935 // We are part of an if-elseif-else chain. Our constraints are tightened.
936 // 7 = "} else " .len()
937 fresh_shape.offset_left(7)?
942 let label_string = rewrite_label(self.label);
943 // 1 = space after keyword.
944 let offset = self.keyword.len() + label_string.len() + 1;
946 let pat_expr_string = match self.cond {
947 Some(cond) => rewrite_pat_expr(
957 None => String::new(),
961 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
967 let one_line_budget = context
970 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
972 let force_newline_brace = (pat_expr_string.contains('\n')
973 || pat_expr_string.len() > one_line_budget)
974 && !last_line_extendable(&pat_expr_string);
976 // Try to format if-else on single line.
977 if self.allow_single_line
981 .single_line_if_else_max_width > 0
983 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
985 if let Some(cond_str) = trial {
990 .single_line_if_else_max_width
992 return Some((cond_str, 0));
997 let cond_span = if let Some(cond) = self.cond {
1000 mk_sp(self.block.span.lo(), self.block.span.lo())
1003 // `for event in event`
1004 // Do not include label in the span.
1005 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1006 let between_kwd_cond = mk_sp(
1009 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1010 self.pat.map_or(cond_span.lo(), |p| {
1011 if self.matcher.is_empty() {
1016 .span_before(self.span, self.matcher.trim())
1021 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1023 let after_cond_comment =
1024 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1026 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1028 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1029 || force_newline_brace
1036 let used_width = if pat_expr_string.contains('\n') {
1037 last_line_width(&pat_expr_string)
1039 // 2 = spaces after keyword and condition.
1040 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1048 between_kwd_cond_comment.as_ref().map_or(
1049 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1057 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1064 impl<'a> Rewrite for ControlFlow<'a> {
1065 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1066 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1068 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1069 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1070 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1071 if used_width == 0 {
1072 return Some(cond_str);
1075 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1076 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1077 // we should avoid the single line case.
1078 let block_width = if self.else_block.is_some() || self.nested_if {
1083 let block_shape = Shape {
1087 let mut block_context = context.clone();
1088 block_context.is_if_else_block = self.else_block.is_some();
1090 rewrite_block_with_visitor(&block_context, "", self.block, block_shape, true)?;
1092 let mut result = format!("{}{}", cond_str, block_str);
1094 if let Some(else_block) = self.else_block {
1095 let shape = Shape::indented(shape.indent, context.config);
1096 let mut last_in_chain = false;
1097 let rewrite = match else_block.node {
1098 // If the else expression is another if-else expression, prevent it
1099 // from being formatted on a single line.
1100 // Note how we're passing the original shape, as the
1101 // cost of "else" should not cascade.
1102 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1103 ControlFlow::new_if(
1107 next_else_block.as_ref().map(|e| &**e),
1110 mk_sp(else_block.span.lo(), self.span.hi()),
1111 ).rewrite(context, shape)
1113 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1114 ControlFlow::new_if(
1118 next_else_block.as_ref().map(|e| &**e),
1121 mk_sp(else_block.span.lo(), self.span.hi()),
1122 ).rewrite(context, shape)
1125 last_in_chain = true;
1126 // When rewriting a block, the width is only used for single line
1127 // blocks, passing 1 lets us avoid that.
1128 let else_shape = Shape {
1129 width: min(1, shape.width),
1132 format_expr(else_block, ExprType::Statement, context, else_shape)
1136 let between_kwd_else_block = mk_sp(
1137 self.block.span.hi(),
1140 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1142 let between_kwd_else_block_comment =
1143 extract_comment(between_kwd_else_block, context, shape);
1145 let after_else = mk_sp(
1148 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1149 else_block.span.lo(),
1151 let after_else_comment = extract_comment(after_else, context, shape);
1153 let between_sep = match context.config.control_brace_style() {
1154 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1157 ControlBraceStyle::AlwaysSameLine => " ",
1159 let after_sep = match context.config.control_brace_style() {
1160 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1164 result.push_str(&format!(
1166 between_kwd_else_block_comment
1168 .map_or(between_sep, |s| &**s),
1169 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1171 result.push_str(&rewrite?);
1178 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1180 Some(label) => Cow::from(format!("{}: ", label.ident)),
1181 None => Cow::from(""),
1185 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1186 match rewrite_missing_comment(span, shape, context) {
1187 Some(ref comment) if !comment.is_empty() => Some(format!(
1188 "{indent}{}{indent}",
1190 indent = shape.indent.to_string_with_newline(context.config)
1196 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1197 let snippet = codemap.span_to_snippet(block.span).unwrap();
1198 contains_comment(&snippet)
1201 // Checks that a block contains no statements, an expression and no comments.
1202 // FIXME: incorrectly returns false when comment is contained completely within
1204 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1205 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1206 && !block_contains_comment(block, codemap))
1209 /// Checks whether a block contains at most one statement or expression, and no comments.
1210 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1211 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1214 /// Checks whether a block contains no statements, expressions, or comments.
1215 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1216 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1219 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1221 ast::StmtKind::Expr(..) => true,
1226 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1227 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1234 /// A simple wrapper type against ast::Arm. Used inside write_list().
1235 struct ArmWrapper<'a> {
1236 pub arm: &'a ast::Arm,
1237 /// True if the arm is the last one in match expression. Used to decide on whether we should add
1238 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
1240 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
1241 pub beginning_vert: Option<BytePos>,
1244 impl<'a> ArmWrapper<'a> {
1248 beginning_vert: Option<BytePos>,
1249 ) -> ArmWrapper<'a> {
1258 impl<'a> Spanned for ArmWrapper<'a> {
1259 fn span(&self) -> Span {
1260 if let Some(lo) = self.beginning_vert {
1261 mk_sp(lo, self.arm.span().hi())
1268 impl<'a> Rewrite for ArmWrapper<'a> {
1269 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1270 rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
1275 context: &RewriteContext,
1280 attrs: &[ast::Attribute],
1281 ) -> Option<String> {
1282 // Do not take the rhs overhead from the upper expressions into account
1283 // when rewriting match condition.
1284 let cond_shape = Shape {
1285 width: context.budget(shape.used_width()),
1289 let cond_shape = match context.config.indent_style() {
1290 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1291 IndentStyle::Block => cond_shape.offset_left(6)?,
1293 let cond_str = cond.rewrite(context, cond_shape)?;
1294 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1295 let block_sep = match context.config.control_brace_style() {
1296 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1297 _ if last_line_extendable(&cond_str) => " ",
1299 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
1303 let nested_indent_str = shape
1305 .block_indent(context.config)
1306 .to_string(context.config);
1307 // Inner attributes.
1308 let inner_attrs = &inner_attributes(attrs);
1309 let inner_attrs_str = if inner_attrs.is_empty() {
1313 .rewrite(context, shape)
1314 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1317 let open_brace_pos = if inner_attrs.is_empty() {
1318 let hi = if arms.is_empty() {
1325 .span_after(mk_sp(cond.span.hi(), hi), "{")
1327 inner_attrs[inner_attrs.len() - 1].span().hi()
1330 if arms.is_empty() {
1331 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1332 if snippet.trim().is_empty() {
1333 Some(format!("match {} {{}}", cond_str))
1335 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1336 Some(context.snippet(span).to_owned())
1340 "match {}{}{{\n{}{}{}\n{}}}",
1345 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1346 shape.indent.to_string(context.config),
1351 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1352 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1354 } else if config.match_block_trailing_comma() {
1356 } else if let ast::ExprKind::Block(ref block) = body.node {
1357 if let ast::BlockCheckMode::Default = block.rules {
1367 /// Collect a byte position of the beginning `|` for each arm, if available.
1368 fn collect_beginning_verts(
1369 context: &RewriteContext,
1372 ) -> Vec<Option<BytePos>> {
1373 let mut beginning_verts = Vec::with_capacity(arms.len());
1374 let mut lo = context.snippet_provider.span_after(span, "{");
1376 let hi = arm.pats[0].span.lo();
1377 let missing_span = mk_sp(lo, hi);
1378 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
1379 lo = arm.span().hi();
1384 fn rewrite_match_arms(
1385 context: &RewriteContext,
1389 open_brace_pos: BytePos,
1390 ) -> Option<String> {
1391 let arm_shape = shape
1392 .block_indent(context.config.tab_spaces())
1393 .with_max_width(context.config);
1395 let arm_len = arms.len();
1396 let is_last_iter = repeat(false)
1397 .take(arm_len.checked_sub(1).unwrap_or(0))
1398 .chain(repeat(true));
1399 let beginning_verts = collect_beginning_verts(context, arms, span);
1400 let items = itemize_list(
1401 context.snippet_provider,
1404 .zip(beginning_verts.into_iter())
1405 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
1408 |arm| arm.span().lo(),
1409 |arm| arm.span().hi(),
1410 |arm| arm.rewrite(context, arm_shape),
1415 let arms_vec: Vec<_> = items.collect();
1416 let fmt = ListFormatting {
1417 tactic: DefinitiveListTactic::Vertical,
1418 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1420 trailing_separator: SeparatorTactic::Never,
1421 separator_place: SeparatorPlace::Back,
1423 ends_with_newline: true,
1424 preserve_newline: true,
1425 config: context.config,
1428 write_list(&arms_vec, &fmt)
1431 fn rewrite_match_arm(
1432 context: &RewriteContext,
1436 beginning_vert: Option<BytePos>,
1437 ) -> Option<String> {
1438 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1439 if contains_skip(&arm.attrs) {
1440 let (_, body) = flatten_arm_body(context, &arm.body);
1441 // `arm.span()` does not include trailing comma, add it manually.
1442 return Some(format!(
1444 context.snippet(arm.span()),
1445 arm_comma(context.config, body, is_last),
1448 let missing_span = mk_sp(
1449 arm.attrs[arm.attrs.len() - 1].span.hi(),
1450 arm.pats[0].span.lo(),
1452 (missing_span, arm.attrs.rewrite(context, shape)?)
1454 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1456 let pats_str = rewrite_match_pattern(
1460 beginning_vert.is_some(),
1462 ).and_then(|pats_str| {
1463 combine_strs_with_missing_comments(
1477 arm.guard.is_some(),
1482 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
1486 /// - `&[single-line, ntp]`
1489 /// - `[small, ntp]`
1490 /// - unary tuple constructor `([small, ntp])`
1492 fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
1493 // We also require that the pattern is reasonably 'small' with its literal width.
1494 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
1497 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
1499 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
1500 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
1501 ast::PatKind::Struct(..)
1502 | ast::PatKind::Mac(..)
1503 | ast::PatKind::Slice(..)
1504 | ast::PatKind::Path(..)
1505 | ast::PatKind::Range(..) => false,
1506 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
1507 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
1508 path.segments.len() <= 1 && subpats.len() <= 1
1510 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) => is_short_pattern_inner(&*p),
1514 fn rewrite_match_pattern(
1515 context: &RewriteContext,
1516 pats: &[ptr::P<ast::Pat>],
1517 guard: &Option<ptr::P<ast::Expr>>,
1518 has_beginning_vert: bool,
1520 ) -> Option<String> {
1524 let pat_shape = shape
1526 .offset_left(if has_beginning_vert { 2 } else { 0 })?;
1528 let pat_strs = pats.iter()
1529 .map(|p| p.rewrite(context, pat_shape))
1530 .collect::<Option<Vec<_>>>()?;
1532 let use_mixed_layout = pats.iter()
1533 .zip(pat_strs.iter())
1534 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1535 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1536 let tactic = if use_mixed_layout {
1537 DefinitiveListTactic::Mixed
1541 ListTactic::HorizontalVertical,
1542 Separator::VerticalBar,
1546 let fmt = ListFormatting {
1549 trailing_separator: SeparatorTactic::Never,
1550 separator_place: context.config.binop_separator(),
1552 ends_with_newline: false,
1553 preserve_newline: false,
1554 config: context.config,
1556 let pats_str = write_list(&items, &fmt)?;
1557 let beginning_vert = if has_beginning_vert { "| " } else { "" };
1560 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1562 Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
1566 // @extend: true if the arm body can be put next to `=>`
1567 // @body: flattened body, if the body is block with a single expression
1568 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1570 ast::ExprKind::Block(ref block)
1571 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1573 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1575 !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
1583 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
1589 fn rewrite_match_body(
1590 context: &RewriteContext,
1591 body: &ptr::P<ast::Expr>,
1596 ) -> Option<String> {
1597 let (extend, body) = flatten_arm_body(context, body);
1598 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1599 (true, is_empty_block(block, context.codemap))
1604 let comma = arm_comma(context.config, body, is_last);
1605 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1607 let combine_orig_body = |body_str: &str| {
1608 let block_sep = match context.config.control_brace_style() {
1609 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1613 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1616 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1617 let next_line_indent = if !is_block || is_empty_block {
1618 shape.indent.block_indent(context.config)
1622 let combine_next_line_body = |body_str: &str| {
1624 return Some(format!(
1627 next_line_indent.to_string_with_newline(context.config),
1632 let indent_str = shape.indent.to_string_with_newline(context.config);
1633 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
1634 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
1635 let comma = if context.config.match_block_trailing_comma() {
1640 ("{", format!("{}}}{}", indent_str, comma))
1642 ("", String::from(","))
1645 let block_sep = match context.config.control_brace_style() {
1646 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
1647 _ if body_prefix.is_empty() => "".to_owned(),
1648 _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
1649 _ => format!(" {}", body_prefix),
1650 } + &nested_indent_str;
1654 pats_str, block_sep, body_str, body_suffix
1658 // Let's try and get the arm body on the same line as the condition.
1660 let orig_body_shape = shape
1661 .offset_left(extra_offset(pats_str, shape) + 4)
1662 .and_then(|shape| shape.sub_width(comma.len()));
1663 let orig_body = if let Some(body_shape) = orig_body_shape {
1664 let rewrite = nop_block_collapse(
1665 format_expr(body, ExprType::Statement, context, body_shape),
1671 if !forbid_same_line
1673 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1675 return combine_orig_body(body_str);
1682 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1684 // Try putting body on the next line and see if it looks better.
1685 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1686 let next_line_body = nop_block_collapse(
1687 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1688 next_line_body_shape.width,
1690 match (orig_body, next_line_body) {
1691 (Some(ref orig_str), Some(ref next_line_str))
1692 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1694 combine_next_line_body(next_line_str)
1696 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1697 combine_orig_body(orig_str)
1699 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1700 combine_next_line_body(next_line_str)
1702 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1703 (None, None) => None,
1704 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1708 // The `if ...` guard on a match arm.
1710 context: &RewriteContext,
1711 guard: &Option<ptr::P<ast::Expr>>,
1713 // The amount of space used up on this line for the pattern in
1714 // the arm (excludes offset).
1715 pattern_width: usize,
1716 ) -> Option<String> {
1717 if let Some(ref guard) = *guard {
1718 // First try to fit the guard string on the same line as the pattern.
1719 // 4 = ` if `, 5 = ` => {`
1720 let cond_shape = shape
1721 .offset_left(pattern_width + 4)
1722 .and_then(|s| s.sub_width(5));
1723 if let Some(cond_shape) = cond_shape {
1724 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1725 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1726 return Some(format!(" if {}", cond_str));
1731 // Not enough space to put the guard after the pattern, try a newline.
1732 // 3 = `if `, 5 = ` => {`
1733 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1735 .and_then(|s| s.sub_width(5));
1736 if let Some(cond_shape) = cond_shape {
1737 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1738 return Some(format!(
1740 cond_shape.indent.to_string_with_newline(context.config),
1752 fn rewrite_pat_expr(
1753 context: &RewriteContext,
1754 pat: Option<&ast::Pat>,
1757 // Connecting piece between pattern and expression,
1758 // *without* trailing space.
1763 ) -> Option<String> {
1764 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1765 let cond_shape = shape.offset_left(offset)?;
1766 if let Some(pat) = pat {
1767 let matcher = if matcher.is_empty() {
1770 format!("{} ", matcher)
1772 let pat_shape = cond_shape
1773 .offset_left(matcher.len())?
1774 .sub_width(connector.len())?;
1775 let pat_string = pat.rewrite(context, pat_shape)?;
1776 let result = format!("{}{}{}", matcher, pat_string, connector);
1777 return rewrite_assign_rhs(context, result, expr, cond_shape);
1780 let expr_rw = expr.rewrite(context, cond_shape);
1781 // The expression may (partially) fit on the current line.
1782 // We do not allow splitting between `if` and condition.
1783 if keyword == "if" || expr_rw.is_some() {
1787 // The expression won't fit on the current line, jump to next.
1788 let nested_shape = shape
1789 .block_indent(context.config.tab_spaces())
1790 .with_max_width(context.config);
1791 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
1792 expr.rewrite(context, nested_shape)
1793 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
1796 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
1798 // We do not allow `if` to stay on the same line, since we could easily mistake
1799 // `pat => if cond { ... }` and `pat if cond => { ... }`.
1800 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
1801 ast::ExprKind::ForLoop(..)
1802 | ast::ExprKind::Loop(..)
1803 | ast::ExprKind::While(..)
1804 | ast::ExprKind::WhileLet(..)
1805 | ast::ExprKind::Match(..)
1806 | ast::ExprKind::Block(..)
1807 | ast::ExprKind::Closure(..)
1808 | ast::ExprKind::Array(..)
1809 | ast::ExprKind::Call(..)
1810 | ast::ExprKind::MethodCall(..)
1811 | ast::ExprKind::Mac(..)
1812 | ast::ExprKind::Struct(..)
1813 | ast::ExprKind::Tup(..) => true,
1814 ast::ExprKind::AddrOf(_, ref expr)
1815 | ast::ExprKind::Box(ref expr)
1816 | ast::ExprKind::Try(ref expr)
1817 | ast::ExprKind::Unary(_, ref expr)
1818 | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
1823 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1825 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1827 context.snippet(l.span).to_owned(),
1828 context.config.max_width(),
1834 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1835 let string_lit = context.snippet(span);
1837 if !context.config.format_strings() {
1842 .all(|line| line.ends_with('\\'))
1844 let new_indent = shape.visual_indent(1).indent;
1845 let indented_string_lit = String::from(
1851 new_indent.to_string(context.config),
1855 .collect::<Vec<_>>()
1859 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1861 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1865 // Remove the quote characters.
1866 let str_lit = &string_lit[1..string_lit.len() - 1];
1870 &StringFormat::new(shape.visual_indent(0), context.config),
1875 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1878 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1879 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1880 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1881 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1882 // format! like macros
1883 // From the Rust Standard Library.
1887 ("format_args!", 0),
1891 ("unreachable!", 0),
1892 // From the `log` crate.
1897 // write! like macros
1899 ("debug_assert!", 1),
1902 // assert_eq! like macros
1905 ("debug_assert_eq!", 2),
1906 ("debug_assert_ne!", 2),
1909 pub fn rewrite_call(
1910 context: &RewriteContext,
1912 args: &[ptr::P<ast::Expr>],
1915 ) -> Option<String> {
1916 let force_trailing_comma = if context.inside_macro {
1917 span_ends_with_comma(context, span)
1924 &ptr_vec_to_ref_vec(args),
1927 context.config.width_heuristics().fn_call_width,
1928 force_trailing_comma,
1932 pub fn rewrite_call_inner<'a, T>(
1933 context: &RewriteContext,
1938 args_max_width: usize,
1939 force_trailing_comma: bool,
1942 T: Rewrite + Spanned + ToExpr + 'a,
1944 // 2 = `( `, 1 = `(`
1945 let paren_overhead = if context.config.spaces_within_parens_and_brackets() {
1950 let used_width = extra_offset(callee_str, shape);
1951 let one_line_width = shape
1953 .checked_sub(used_width + 2 * paren_overhead)
1957 let one_line_shape = shape
1958 .offset_left(last_line_width(callee_str) + 1)
1959 .and_then(|shape| shape.sub_width(1))
1960 .unwrap_or(Shape { width: 0, ..shape });
1961 let nested_shape = shape_from_indent_style(
1964 used_width + 2 * paren_overhead,
1965 used_width + paren_overhead,
1968 let span_lo = context.snippet_provider.span_after(span, "(");
1969 let args_span = mk_sp(span_lo, span.hi());
1971 let (extendable, list_str) = rewrite_call_args(
1979 force_trailing_comma,
1983 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
1984 let mut new_context = context.clone();
1985 new_context.use_block = true;
1986 return rewrite_call_inner(
1993 force_trailing_comma,
1997 let args_shape = Shape {
2000 .checked_sub(last_line_width(callee_str))
2007 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2011 fn need_block_indent(s: &str, shape: Shape) -> bool {
2012 s.lines().skip(1).any(|s| {
2013 s.find(|c| !char::is_whitespace(c))
2014 .map_or(false, |w| w + 1 < shape.indent.width())
2018 fn rewrite_call_args<'a, T>(
2019 context: &RewriteContext,
2022 one_line_shape: Shape,
2023 nested_shape: Shape,
2024 one_line_width: usize,
2025 args_max_width: usize,
2026 force_trailing_comma: bool,
2028 ) -> Option<(bool, String)>
2030 T: Rewrite + Spanned + ToExpr + 'a,
2032 let items = itemize_list(
2033 context.snippet_provider,
2037 |item| item.span().lo(),
2038 |item| item.span().hi(),
2039 |item| item.rewrite(context, nested_shape),
2044 let mut item_vec: Vec<_> = items.collect();
2046 // Try letting the last argument overflow to the next line with block
2047 // indentation. If its first line fits on one line with the other arguments,
2048 // we format the function arguments horizontally.
2049 let tactic = try_overflow_last_arg(
2060 let fmt = ListFormatting {
2063 trailing_separator: if force_trailing_comma {
2064 SeparatorTactic::Always
2065 } else if context.inside_macro || !context.use_block_indent() {
2066 SeparatorTactic::Never
2068 context.config.trailing_comma()
2070 separator_place: SeparatorPlace::Back,
2071 shape: nested_shape,
2072 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2073 preserve_newline: false,
2074 config: context.config,
2077 write_list(&item_vec, &fmt)
2078 .map(|args_str| (tactic == DefinitiveListTactic::Horizontal, args_str))
2081 fn try_overflow_last_arg<'a, T>(
2082 context: &RewriteContext,
2083 item_vec: &mut Vec<ListItem>,
2085 one_line_shape: Shape,
2086 nested_shape: Shape,
2087 one_line_width: usize,
2088 args_max_width: usize,
2090 ) -> DefinitiveListTactic
2092 T: Rewrite + Spanned + ToExpr + 'a,
2095 let combine_arg_with_callee =
2096 callee_str.len() + 1 <= context.config.tab_spaces() && args.len() == 1;
2097 let overflow_last = combine_arg_with_callee || can_be_overflowed(context, args);
2099 // Replace the last item with its first line to see if it fits with
2101 let placeholder = if overflow_last {
2102 let mut context = context.clone();
2103 if !combine_arg_with_callee {
2104 if let Some(expr) = args[args.len() - 1].to_expr() {
2105 if let ast::ExprKind::MethodCall(..) = expr.node {
2106 context.force_one_line_chain = true;
2110 last_arg_shape(args, item_vec, one_line_shape, args_max_width).and_then(|arg_shape| {
2111 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2117 let mut tactic = definitive_tactic(
2119 ListTactic::LimitedHorizontalVertical(args_max_width),
2124 // Replace the stub with the full overflowing last argument if the rewrite
2125 // succeeded and its first line fits with the other arguments.
2126 match (overflow_last, tactic, placeholder) {
2127 (true, DefinitiveListTactic::Horizontal, Some(ref overflowed)) if args.len() == 1 => {
2128 // When we are rewriting a nested function call, we restrict the
2129 // bugdet for the inner function to avoid them being deeply nested.
2130 // However, when the inner function has a prefix or a suffix
2131 // (e.g. `foo() as u32`), this budget reduction may produce poorly
2132 // formatted code, where a prefix or a suffix being left on its own
2133 // line. Here we explicitlly check those cases.
2134 if count_newlines(overflowed) == 1 {
2135 let rw = args.last()
2136 .and_then(|last_arg| last_arg.rewrite(context, nested_shape));
2137 let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
2139 item_vec[args.len() - 1].item = rw;
2141 item_vec[args.len() - 1].item = Some(overflowed.to_owned());
2144 item_vec[args.len() - 1].item = Some(overflowed.to_owned());
2147 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2148 item_vec[args.len() - 1].item = placeholder;
2150 _ if args.len() >= 1 => {
2151 item_vec[args.len() - 1].item = args.last()
2152 .and_then(|last_arg| last_arg.rewrite(context, nested_shape));
2154 let default_tactic = || {
2157 ListTactic::LimitedHorizontalVertical(args_max_width),
2163 // Use horizontal layout for a function with a single argument as long as
2164 // everything fits in a single line.
2166 && args_max_width != 0 // Vertical layout is forced.
2167 && !item_vec[0].has_comment()
2168 && !item_vec[0].inner_as_ref().contains('\n')
2169 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
2171 tactic = DefinitiveListTactic::Horizontal;
2173 tactic = default_tactic();
2175 if tactic == DefinitiveListTactic::Vertical {
2176 if let Some((all_simple, num_args_before)) =
2177 maybe_get_args_offset(callee_str, args)
2179 let one_line = all_simple
2180 && definitive_tactic(
2181 &item_vec[..num_args_before],
2182 ListTactic::HorizontalVertical,
2185 ) == DefinitiveListTactic::Horizontal
2186 && definitive_tactic(
2187 &item_vec[num_args_before + 1..],
2188 ListTactic::HorizontalVertical,
2191 ) == DefinitiveListTactic::Horizontal;
2194 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
2206 fn is_simple_arg(expr: &ast::Expr) -> bool {
2208 ast::ExprKind::Lit(..) => true,
2209 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
2210 ast::ExprKind::AddrOf(_, ref expr)
2211 | ast::ExprKind::Box(ref expr)
2212 | ast::ExprKind::Cast(ref expr, _)
2213 | ast::ExprKind::Field(ref expr, _)
2214 | ast::ExprKind::Try(ref expr)
2215 | ast::ExprKind::TupField(ref expr, _)
2216 | ast::ExprKind::Unary(_, ref expr) => is_simple_arg(expr),
2217 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
2218 is_simple_arg(lhs) && is_simple_arg(rhs)
2224 fn is_every_args_simple<T: ToExpr>(lists: &[&T]) -> bool {
2227 .all(|arg| arg.to_expr().map_or(false, is_simple_arg))
2230 /// In case special-case style is required, returns an offset from which we start horizontal layout.
2231 fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
2232 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
2234 .find(|&&(s, _)| s == callee_str)
2236 let all_simple = args.len() > num_args_before && is_every_args_simple(args);
2238 Some((all_simple, num_args_before))
2244 /// Returns a shape for the last argument which is going to be overflowed.
2245 fn last_arg_shape<T>(
2249 args_max_width: usize,
2252 T: Rewrite + Spanned + ToExpr,
2254 let is_nested_call = lists
2257 .and_then(|item| item.to_expr())
2258 .map_or(false, is_nested_call);
2259 if items.len() == 1 && !is_nested_call {
2262 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
2264 acc + 2 + i.inner_as_ref().len()
2267 width: min(args_max_width, shape.width),
2269 }.offset_left(offset)
2272 fn rewrite_last_arg_with_overflow<'a, T>(
2273 context: &RewriteContext,
2275 last_item: &mut ListItem,
2279 T: Rewrite + Spanned + ToExpr + 'a,
2281 let last_arg = args[args.len() - 1];
2282 let rewrite = if let Some(expr) = last_arg.to_expr() {
2284 // When overflowing the closure which consists of a single control flow expression,
2285 // force to use block if its condition uses multi line.
2286 ast::ExprKind::Closure(..) => {
2287 // If the argument consists of multiple closures, we do not overflow
2288 // the last closure.
2289 if closures::args_have_many_closure(args) {
2292 closures::rewrite_last_closure(context, expr, shape)
2295 _ => expr.rewrite(context, shape),
2298 last_arg.rewrite(context, shape)
2301 if let Some(rewrite) = rewrite {
2302 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2303 last_item.item = rewrite_first_line;
2310 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2312 T: Rewrite + Spanned + ToExpr + 'a,
2315 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2318 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2320 ast::ExprKind::Match(..) => {
2321 (context.use_block_indent() && args_len == 1)
2322 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
2324 ast::ExprKind::If(..)
2325 | ast::ExprKind::IfLet(..)
2326 | ast::ExprKind::ForLoop(..)
2327 | ast::ExprKind::Loop(..)
2328 | ast::ExprKind::While(..)
2329 | ast::ExprKind::WhileLet(..) => {
2330 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2332 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2333 context.use_block_indent()
2334 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
2336 ast::ExprKind::Array(..)
2337 | ast::ExprKind::Call(..)
2338 | ast::ExprKind::Mac(..)
2339 | ast::ExprKind::MethodCall(..)
2340 | ast::ExprKind::Struct(..)
2341 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2342 ast::ExprKind::AddrOf(_, ref expr)
2343 | ast::ExprKind::Box(ref expr)
2344 | ast::ExprKind::Try(ref expr)
2345 | ast::ExprKind::Unary(_, ref expr)
2346 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2351 fn is_nested_call(expr: &ast::Expr) -> bool {
2353 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
2354 ast::ExprKind::AddrOf(_, ref expr)
2355 | ast::ExprKind::Box(ref expr)
2356 | ast::ExprKind::Try(ref expr)
2357 | ast::ExprKind::Unary(_, ref expr)
2358 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
2363 pub fn wrap_args_with_parens(
2364 context: &RewriteContext,
2366 is_extendable: bool,
2368 nested_shape: Shape,
2370 let paren_overhead = paren_overhead(context);
2371 let fits_one_line = args_str.len() + paren_overhead <= shape.width;
2372 let extend_width = if args_str.is_empty() {
2377 if !context.use_block_indent()
2378 || (context.inside_macro && !args_str.contains('\n') && fits_one_line)
2379 || (is_extendable && extend_width <= shape.width)
2381 let mut result = String::with_capacity(args_str.len() + 4);
2382 if context.config.spaces_within_parens_and_brackets() && !args_str.is_empty() {
2383 result.push_str("( ");
2384 result.push_str(args_str);
2385 result.push_str(" )");
2387 result.push_str("(");
2388 result.push_str(args_str);
2389 result.push_str(")");
2393 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
2394 let indent_str = shape.block().indent.to_string_with_newline(context.config);
2396 String::with_capacity(args_str.len() + 2 + indent_str.len() + nested_indent_str.len());
2397 result.push_str("(");
2398 if !args_str.is_empty() {
2399 result.push_str(&nested_indent_str);
2400 result.push_str(args_str);
2402 result.push_str(&indent_str);
2403 result.push_str(")");
2408 /// Return true if a function call or a method call represented by the given span ends with a
2409 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2410 /// comma from macro can potentially break the code.
2411 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2412 let mut encountered_closing_paren = false;
2413 for c in context.snippet(span).chars().rev() {
2416 ')' => if encountered_closing_paren {
2419 encountered_closing_paren = true;
2421 _ if c.is_whitespace() => continue,
2428 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2429 debug!("rewrite_paren, shape: {:?}", shape);
2430 let total_paren_overhead = paren_overhead(context);
2431 let paren_overhead = total_paren_overhead / 2;
2432 let sub_shape = shape
2433 .offset_left(paren_overhead)
2434 .and_then(|s| s.sub_width(paren_overhead))?;
2436 let paren_wrapper = |s: &str| {
2437 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2438 format!("( {} )", s)
2444 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2445 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2447 if subexpr_str.contains('\n')
2448 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2450 Some(paren_wrapper(&subexpr_str))
2459 context: &RewriteContext,
2461 ) -> Option<String> {
2462 let expr_str = expr.rewrite(context, shape)?;
2464 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2470 let offset = last_line_width(&expr_str) + lbr.len();
2471 let rhs_overhead = shape.rhs_overhead(context.config);
2472 let index_shape = if expr_str.contains('\n') {
2473 Shape::legacy(context.config.max_width(), shape.indent)
2474 .offset_left(offset)
2475 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2477 shape.visual_indent(offset).sub_width(offset + rbr.len())
2479 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2481 // Return if index fits in a single line.
2482 match orig_index_rw {
2483 Some(ref index_str) if !index_str.contains('\n') => {
2484 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2489 // Try putting index on the next line and see if it fits in a single line.
2490 let indent = shape.indent.block_indent(context.config);
2491 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2492 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2493 let new_index_rw = index.rewrite(context, index_shape);
2494 match (orig_index_rw, new_index_rw) {
2495 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2498 indent.to_string_with_newline(context.config),
2503 (None, Some(ref new_index_str)) => Some(format!(
2506 indent.to_string_with_newline(context.config),
2511 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2516 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2521 fields.iter().all(|field| !field.is_shorthand)
2524 fn rewrite_struct_lit<'a>(
2525 context: &RewriteContext,
2527 fields: &'a [ast::Field],
2528 base: Option<&'a ast::Expr>,
2531 ) -> Option<String> {
2532 debug!("rewrite_struct_lit: shape {:?}", shape);
2534 enum StructLitField<'a> {
2535 Regular(&'a ast::Field),
2536 Base(&'a ast::Expr),
2540 let path_shape = shape.sub_width(2)?;
2541 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2543 if fields.is_empty() && base.is_none() {
2544 return Some(format!("{} {{}}", path_str));
2547 // Foo { a: Foo } - indent is +3, width is -5.
2548 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2550 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2551 let body_lo = context.snippet_provider.span_after(span, "{");
2552 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2553 && context.config.struct_field_align_threshold() > 0
2555 rewrite_with_alignment(
2559 mk_sp(body_lo, span.hi()),
2563 let field_iter = fields
2565 .map(StructLitField::Regular)
2566 .chain(base.into_iter().map(StructLitField::Base));
2568 let span_lo = |item: &StructLitField| match *item {
2569 StructLitField::Regular(field) => field.span().lo(),
2570 StructLitField::Base(expr) => {
2571 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2572 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2573 let pos = snippet.find_uncommented("..").unwrap();
2574 last_field_hi + BytePos(pos as u32)
2577 let span_hi = |item: &StructLitField| match *item {
2578 StructLitField::Regular(field) => field.span().hi(),
2579 StructLitField::Base(expr) => expr.span.hi(),
2581 let rewrite = |item: &StructLitField| match *item {
2582 StructLitField::Regular(field) => {
2583 // The 1 taken from the v_budget is for the comma.
2584 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2586 StructLitField::Base(expr) => {
2588 expr.rewrite(context, v_shape.offset_left(2)?)
2589 .map(|s| format!("..{}", s))
2593 let items = itemize_list(
2594 context.snippet_provider,
2605 let item_vec = items.collect::<Vec<_>>();
2607 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2608 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2609 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2611 write_list(&item_vec, &fmt)?
2614 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2615 Some(format!("{} {{{}}}", path_str, fields_str))
2617 // FIXME if context.config.indent_style() == Visual, but we run out
2618 // of space, we should fall back to BlockIndent.
2621 pub fn wrap_struct_field(
2622 context: &RewriteContext,
2625 nested_shape: Shape,
2626 one_line_width: usize,
2628 if context.config.indent_style() == IndentStyle::Block
2629 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
2630 || fields_str.len() > one_line_width)
2634 nested_shape.indent.to_string_with_newline(context.config),
2636 shape.indent.to_string_with_newline(context.config)
2639 // One liner or visual indent.
2640 format!(" {} ", fields_str)
2644 pub fn struct_lit_field_separator(config: &Config) -> &str {
2645 colon_spaces(config.space_before_colon(), config.space_after_colon())
2648 pub fn rewrite_field(
2649 context: &RewriteContext,
2652 prefix_max_width: usize,
2653 ) -> Option<String> {
2654 if contains_skip(&field.attrs) {
2655 return Some(context.snippet(field.span()).to_owned());
2657 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2658 if !attrs_str.is_empty() {
2659 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
2661 let name = field.ident.node.to_string();
2662 if field.is_shorthand {
2663 Some(attrs_str + &name)
2665 let mut separator = String::from(struct_lit_field_separator(context.config));
2666 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2667 separator.push(' ');
2669 let overhead = name.len() + separator.len();
2670 let expr_shape = shape.offset_left(overhead)?;
2671 let expr = field.expr.rewrite(context, expr_shape);
2674 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
2675 Some(attrs_str + &name)
2677 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2679 let expr_offset = shape.indent.block_indent(context.config);
2682 .rewrite(context, Shape::indented(expr_offset, context.config));
2688 expr_offset.to_string(context.config),
2697 fn shape_from_indent_style(
2698 context: &RewriteContext,
2702 ) -> Option<Shape> {
2703 if context.use_block_indent() {
2707 .block_indent(context.config.tab_spaces())
2708 .with_max_width(context.config)
2711 shape.visual_indent(offset).sub_width(overhead)
2715 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2716 context: &RewriteContext,
2722 T: Rewrite + Spanned + ToExpr + 'a,
2724 let mut items = items.iter();
2725 // In case of length 1, need a trailing comma
2726 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2727 if items.len() == 1 {
2729 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2733 .rewrite(context, nested_shape)
2735 if context.config.spaces_within_parens_and_brackets() {
2736 format!("( {}, )", s)
2743 let list_lo = context.snippet_provider.span_after(span, "(");
2744 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2745 let items = itemize_list(
2746 context.snippet_provider,
2750 |item| item.span().lo(),
2751 |item| item.span().hi(),
2752 |item| item.rewrite(context, nested_shape),
2754 span.hi() - BytePos(1),
2757 let item_vec: Vec<_> = items.collect();
2758 let tactic = definitive_tactic(
2760 ListTactic::HorizontalVertical,
2764 let fmt = ListFormatting {
2767 trailing_separator: SeparatorTactic::Never,
2768 separator_place: SeparatorPlace::Back,
2770 ends_with_newline: false,
2771 preserve_newline: false,
2772 config: context.config,
2774 let list_str = write_list(&item_vec, &fmt)?;
2776 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2777 Some(format!("( {} )", list_str))
2779 Some(format!("({})", list_str))
2783 pub fn rewrite_tuple<'a, T>(
2784 context: &RewriteContext,
2790 T: Rewrite + Spanned + ToExpr + 'a,
2792 debug!("rewrite_tuple {:?}", shape);
2793 if context.use_block_indent() {
2794 // We use the same rule as function calls for rewriting tuples.
2795 let force_trailing_comma = if context.inside_macro {
2796 span_ends_with_comma(context, span)
2806 context.config.width_heuristics().fn_call_width,
2807 force_trailing_comma,
2810 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2814 pub fn rewrite_unary_prefix<R: Rewrite>(
2815 context: &RewriteContext,
2819 ) -> Option<String> {
2821 .rewrite(context, shape.offset_left(prefix.len())?)
2822 .map(|r| format!("{}{}", prefix, r))
2825 // FIXME: this is probably not correct for multi-line Rewrites. we should
2826 // subtract suffix.len() from the last line budget, not the first!
2827 pub fn rewrite_unary_suffix<R: Rewrite>(
2828 context: &RewriteContext,
2832 ) -> Option<String> {
2834 .rewrite(context, shape.sub_width(suffix.len())?)
2841 fn rewrite_unary_op(
2842 context: &RewriteContext,
2846 ) -> Option<String> {
2847 // For some reason, an UnOp is not spanned like BinOp!
2848 let operator_str = match *op {
2849 ast::UnOp::Deref => "*",
2850 ast::UnOp::Not => "!",
2851 ast::UnOp::Neg => "-",
2853 rewrite_unary_prefix(context, operator_str, expr, shape)
2856 fn rewrite_assignment(
2857 context: &RewriteContext,
2860 op: Option<&ast::BinOp>,
2862 ) -> Option<String> {
2863 let operator_str = match op {
2864 Some(op) => context.snippet(op.span),
2868 // 1 = space between lhs and operator.
2869 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2870 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2872 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2875 // The left hand side must contain everything up to, and including, the
2876 // assignment operator.
2877 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2878 context: &RewriteContext,
2882 ) -> Option<String> {
2883 let lhs = lhs.into();
2884 let last_line_width = last_line_width(&lhs)
2885 .checked_sub(if lhs.contains('\n') {
2886 shape.indent.width()
2891 // 1 = space between operator and rhs.
2892 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2894 offset: shape.offset + last_line_width + 1,
2897 let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2901 pub fn choose_rhs<R: Rewrite>(
2902 context: &RewriteContext,
2905 orig_rhs: Option<String>,
2906 ) -> Option<String> {
2908 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2909 Some(format!(" {}", new_str))
2912 // Expression did not fit on the same line as the identifier.
2913 // Try splitting the line and see if that works better.
2915 Shape::indented(shape.indent.block_indent(context.config), context.config)
2916 .sub_width(shape.rhs_overhead(context.config))?;
2917 let new_rhs = expr.rewrite(context, new_shape);
2918 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2920 match (orig_rhs, new_rhs) {
2921 (Some(ref orig_rhs), Some(ref new_rhs))
2922 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2925 Some(format!(" {}", orig_rhs))
2927 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2928 Some(format!("{}{}", new_indent_str, new_rhs))
2930 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2931 (None, None) => None,
2932 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2938 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2939 !next_line_rhs.contains('\n') || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2942 fn rewrite_expr_addrof(
2943 context: &RewriteContext,
2944 mutability: ast::Mutability,
2947 ) -> Option<String> {
2948 let operator_str = match mutability {
2949 ast::Mutability::Immutable => "&",
2950 ast::Mutability::Mutable => "&mut ",
2952 rewrite_unary_prefix(context, operator_str, expr, shape)
2956 fn to_expr(&self) -> Option<&ast::Expr>;
2957 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2960 impl ToExpr for ast::Expr {
2961 fn to_expr(&self) -> Option<&ast::Expr> {
2965 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2966 can_be_overflowed_expr(context, self, len)
2970 impl ToExpr for ast::Ty {
2971 fn to_expr(&self) -> Option<&ast::Expr> {
2975 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2976 can_be_overflowed_type(context, self, len)
2980 impl<'a> ToExpr for TuplePatField<'a> {
2981 fn to_expr(&self) -> Option<&ast::Expr> {
2985 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2986 can_be_overflowed_pat(context, self, len)
2990 impl<'a> ToExpr for ast::StructField {
2991 fn to_expr(&self) -> Option<&ast::Expr> {
2995 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
3000 impl<'a> ToExpr for MacroArg {
3001 fn to_expr(&self) -> Option<&ast::Expr> {
3003 MacroArg::Expr(ref expr) => Some(expr),
3008 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3010 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
3011 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
3012 MacroArg::Pat(..) => false,