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, ExactSizeIterator};
15 use syntax::{ast, ptr};
16 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, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
28 use macros::{rewrite_macro, MacroArg, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 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, extra_offset, first_line_width, inner_attributes,
35 last_line_extendable, last_line_width, mk_sp, outer_attributes, paren_overhead,
36 ptr_vec_to_ref_vec, semicolon_for_stmt, trimmed_last_line_width, wrap_str};
37 use vertical::rewrite_with_alignment;
38 use visitor::FmtVisitor;
40 impl Rewrite for ast::Expr {
41 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
42 format_expr(self, ExprType::SubExpression, context, shape)
46 #[derive(Copy, Clone, PartialEq)]
55 context: &RewriteContext,
58 skip_out_of_file_lines_range!(context, expr.span);
60 if contains_skip(&*expr.attrs) {
61 return Some(context.snippet(expr.span()).to_owned());
64 let expr_rw = match expr.node {
65 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
66 &ptr_vec_to_ref_vec(expr_vec),
67 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
72 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
73 ast::ExprKind::Call(ref callee, ref args) => {
74 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
75 let callee_str = callee.rewrite(context, shape)?;
76 rewrite_call(context, &callee_str, args, inner_span, shape)
78 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
79 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
80 // FIXME: format comments between operands and operator
84 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
87 context.config.binop_separator(),
90 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
91 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
95 base.as_ref().map(|e| &**e),
99 ast::ExprKind::Tup(ref items) => {
100 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
102 ast::ExprKind::If(..)
103 | ast::ExprKind::IfLet(..)
104 | ast::ExprKind::ForLoop(..)
105 | ast::ExprKind::Loop(..)
106 | ast::ExprKind::While(..)
107 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
108 .and_then(|control_flow| control_flow.rewrite(context, shape)),
109 ast::ExprKind::Block(ref block) => {
111 ExprType::Statement => {
112 if is_unsafe_block(block) {
113 block.rewrite(context, shape)
114 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
115 // Rewrite block without trying to put it in a single line.
118 let prefix = block_prefix(context, block, shape)?;
119 rewrite_block_with_visitor(context, &prefix, block, shape, true)
122 ExprType::SubExpression => block.rewrite(context, shape),
125 ast::ExprKind::Match(ref cond, ref arms) => {
126 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
128 ast::ExprKind::Path(ref qself, ref path) => {
129 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
131 ast::ExprKind::Assign(ref lhs, ref rhs) => {
132 rewrite_assignment(context, lhs, rhs, None, shape)
134 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
135 rewrite_assignment(context, lhs, rhs, Some(op), shape)
137 ast::ExprKind::Continue(ref opt_ident) => {
138 let id_str = match *opt_ident {
139 Some(ident) => format!(" {}", ident.node),
140 None => String::new(),
142 Some(format!("continue{}", id_str))
144 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
145 let id_str = match *opt_ident {
146 Some(ident) => format!(" {}", ident.node),
147 None => String::new(),
150 if let Some(ref expr) = *opt_expr {
151 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
153 Some(format!("break{}", id_str))
156 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
157 rewrite_unary_prefix(context, "yield ", &**expr, shape)
159 Some("yield".to_string())
161 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
162 closures::rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
164 ast::ExprKind::Try(..)
165 | ast::ExprKind::Field(..)
166 | ast::ExprKind::TupField(..)
167 | ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
168 ast::ExprKind::Mac(ref mac) => {
169 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
171 context.snippet(expr.span).to_owned(),
172 context.config.max_width(),
177 ast::ExprKind::Ret(None) => Some("return".to_owned()),
178 ast::ExprKind::Ret(Some(ref expr)) => {
179 rewrite_unary_prefix(context, "return ", &**expr, shape)
181 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
182 ast::ExprKind::AddrOf(mutability, ref expr) => {
183 rewrite_expr_addrof(context, mutability, expr, shape)
185 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
188 PairParts::new("", " as ", ""),
191 SeparatorPlace::Front,
193 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
196 PairParts::new("", ": ", ""),
199 SeparatorPlace::Back,
201 ast::ExprKind::Index(ref expr, ref index) => {
202 rewrite_index(&**expr, &**index, context, shape)
204 ast::ExprKind::Repeat(ref expr, ref repeats) => {
205 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
213 PairParts::new(lbr, "; ", rbr),
216 SeparatorPlace::Back,
219 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
220 let delim = match limits {
221 ast::RangeLimits::HalfOpen => "..",
222 ast::RangeLimits::Closed => "..=",
225 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
227 ast::ExprKind::Lit(ref lit) => match lit.node {
228 ast::LitKind::FloatUnsuffixed(..) => {
229 context.snippet(lit.span).ends_with('.')
237 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
238 (Some(lhs), Some(rhs)) => {
239 let sp_delim = if context.config.spaces_around_ranges() {
240 format!(" {} ", delim)
241 } else if needs_space_before_range(context, lhs) {
242 format!(" {}", delim)
249 PairParts::new("", &sp_delim, ""),
252 SeparatorPlace::Front,
255 (None, Some(rhs)) => {
256 let sp_delim = if context.config.spaces_around_ranges() {
257 format!("{} ", delim)
261 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
263 (Some(lhs), None) => {
264 let sp_delim = if context.config.spaces_around_ranges() {
265 format!(" {}", delim)
269 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
271 (None, None) => Some(delim.to_owned()),
274 // We do not format these expressions yet, but they should still
275 // satisfy our width restrictions.
276 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
277 Some(context.snippet(expr.span).to_owned())
279 ast::ExprKind::Catch(ref block) => {
280 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
284 let budget = shape.width.checked_sub(9).unwrap_or(0);
288 block.rewrite(context, Shape::legacy(budget, shape.indent))?
295 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
296 .and_then(|expr_str| {
297 let attrs = outer_attributes(&expr.attrs);
298 let attrs_str = attrs.rewrite(context, shape)?;
300 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
303 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
307 #[derive(new, Clone, Copy)]
308 pub struct PairParts<'a> {
314 pub fn rewrite_pair<LHS, RHS>(
318 context: &RewriteContext,
320 separator_place: SeparatorPlace,
326 let lhs_overhead = match separator_place {
327 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
328 SeparatorPlace::Front => shape.used_width(),
330 let lhs_shape = Shape {
331 width: context.budget(lhs_overhead),
334 let lhs_result = lhs.rewrite(context, lhs_shape)
335 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
337 // Try to the both lhs and rhs on the same line.
338 let rhs_orig_result = shape
339 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
340 .and_then(|s| s.sub_width(pp.suffix.len()))
341 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
342 if let Some(ref rhs_result) = rhs_orig_result {
343 // If the rhs looks like block expression, we allow it to stay on the same line
344 // with the lhs even if it is multi-lined.
345 let allow_same_line = rhs_result
348 .map(|first_line| first_line.ends_with('{'))
350 if !rhs_result.contains('\n') || allow_same_line {
351 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
352 + first_line_width(rhs_result) + pp.suffix.len();
353 if one_line_width <= shape.width {
356 lhs_result, pp.infix, rhs_result, pp.suffix
362 // We have to use multiple lines.
363 // Re-evaluate the rhs because we have more space now:
364 let mut rhs_shape = match context.config.indent_style() {
365 IndentStyle::Visual => shape
366 .sub_width(pp.suffix.len() + pp.prefix.len())?
367 .visual_indent(pp.prefix.len()),
368 IndentStyle::Block => {
369 // Try to calculate the initial constraint on the right hand side.
370 let rhs_overhead = shape.rhs_overhead(context.config);
371 Shape::indented(shape.indent.block_indent(context.config), context.config)
372 .sub_width(rhs_overhead)?
375 let infix = match separator_place {
376 SeparatorPlace::Back => pp.infix.trim_right(),
377 SeparatorPlace::Front => pp.infix.trim_left(),
379 if separator_place == SeparatorPlace::Front {
380 rhs_shape = rhs_shape.offset_left(infix.len())?;
382 let rhs_result = rhs.rewrite(context, rhs_shape)?;
383 let indent_str = rhs_shape.indent.to_string(context.config);
384 let infix_with_sep = match separator_place {
385 SeparatorPlace::Back => format!("{}\n{}", infix, indent_str),
386 SeparatorPlace::Front => format!("\n{}{}", indent_str, infix),
390 lhs_result, infix_with_sep, rhs_result, pp.suffix
394 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
397 context: &RewriteContext,
399 trailing_comma: bool,
400 ) -> Option<String> {
401 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
407 let nested_shape = match context.config.indent_style() {
408 IndentStyle::Block => shape
410 .block_indent(context.config.tab_spaces())
411 .with_max_width(context.config)
413 IndentStyle::Visual => shape
414 .visual_indent(bracket_size)
415 .sub_width(bracket_size * 2)?,
418 let items = itemize_list(
423 |item| item.span().lo(),
424 |item| item.span().hi(),
425 |item| item.rewrite(context, nested_shape),
429 ).collect::<Vec<_>>();
431 if items.is_empty() {
432 if context.config.spaces_within_parens_and_brackets() {
433 return Some("[ ]".to_string());
435 return Some("[]".to_string());
439 let tactic = array_tactic(context, shape, nested_shape, exprs, &items, bracket_size);
440 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
442 let fmt = ListFormatting {
445 trailing_separator: if trailing_comma {
446 SeparatorTactic::Always
447 } else if context.inside_macro && !exprs.is_empty() {
448 let ends_with_bracket = context.snippet(span).ends_with(']');
449 let bracket_offset = if ends_with_bracket { 1 } else { 0 };
450 let snippet = context.snippet(mk_sp(span.lo(), span.hi() - BytePos(bracket_offset)));
451 let last_char_index = snippet.rfind(|c: char| !c.is_whitespace())?;
452 if &snippet[last_char_index..last_char_index + 1] == "," {
453 SeparatorTactic::Always
455 SeparatorTactic::Never
457 } else if context.config.indent_style() == IndentStyle::Visual {
458 SeparatorTactic::Never
460 SeparatorTactic::Vertical
462 separator_place: SeparatorPlace::Back,
464 ends_with_newline: ends_with_newline,
465 preserve_newline: false,
466 config: context.config,
468 let list_str = write_list(&items, &fmt)?;
470 let result = if context.config.indent_style() == IndentStyle::Visual
471 || tactic == DefinitiveListTactic::Horizontal
473 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
474 format!("[ {} ]", list_str)
476 format!("[{}]", list_str)
481 nested_shape.indent.to_string(context.config),
483 shape.block().indent.to_string(context.config)
490 fn array_tactic<T: Rewrite + Spanned + ToExpr>(
491 context: &RewriteContext,
497 ) -> DefinitiveListTactic {
498 let has_long_item = items
500 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
502 match context.config.indent_style() {
503 IndentStyle::Block => {
504 let tactic = match shape.width.checked_sub(2 * bracket_size) {
506 let tactic = ListTactic::LimitedHorizontalVertical(
507 context.config.width_heuristics().array_width,
509 definitive_tactic(items, tactic, Separator::Comma, width)
511 None => DefinitiveListTactic::Vertical,
513 if tactic == DefinitiveListTactic::Vertical && !has_long_item
514 && is_every_args_simple(exprs)
516 DefinitiveListTactic::Mixed
521 IndentStyle::Visual => {
522 if has_long_item || items.iter().any(ListItem::is_multiline) {
525 ListTactic::LimitedHorizontalVertical(
526 context.config.width_heuristics().array_width,
532 DefinitiveListTactic::Mixed
538 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
539 debug!("nop_block_collapse {:?} {}", block_str, budget);
540 block_str.map(|block_str| {
541 if block_str.starts_with('{') && budget >= 2
542 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
551 fn rewrite_empty_block(
552 context: &RewriteContext,
555 ) -> Option<String> {
556 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
558 return Some("{}".to_owned());
561 // If a block contains only a single-line comment, then leave it on one line.
562 let user_str = context.snippet(block.span);
563 let user_str = user_str.trim();
564 if user_str.starts_with('{') && user_str.ends_with('}') {
565 let comment_str = user_str[1..user_str.len() - 1].trim();
566 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
567 && comment_str.len() + 4 <= shape.width
569 return Some(format!("{{ {} }}", comment_str));
576 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
577 Some(match block.rules {
578 ast::BlockCheckMode::Unsafe(..) => {
579 let snippet = context.snippet(block.span);
580 let open_pos = snippet.find_uncommented("{")?;
581 // Extract comment between unsafe and block start.
582 let trimmed = &snippet[6..open_pos].trim();
584 if !trimmed.is_empty() {
585 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
586 let budget = shape.width.checked_sub(9)?;
592 Shape::legacy(budget, shape.indent + 7),
600 ast::BlockCheckMode::Default => String::new(),
604 fn rewrite_single_line_block(
605 context: &RewriteContext,
609 ) -> Option<String> {
610 if is_simple_block(block, context.codemap) {
611 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
612 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
613 let result = format!("{}{{ {} }}", prefix, expr_str);
614 if result.len() <= shape.width && !result.contains('\n') {
621 pub fn rewrite_block_with_visitor(
622 context: &RewriteContext,
627 ) -> Option<String> {
628 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
632 let mut visitor = FmtVisitor::from_context(context);
633 visitor.block_indent = shape.indent;
634 visitor.is_if_else_block = context.is_if_else_block;
636 ast::BlockCheckMode::Unsafe(..) => {
637 let snippet = context.snippet(block.span);
638 let open_pos = snippet.find_uncommented("{")?;
639 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
641 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
644 visitor.visit_block(block, None, has_braces);
645 Some(format!("{}{}", prefix, visitor.buffer))
648 impl Rewrite for ast::Block {
649 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
650 // shape.width is used only for the single line case: either the empty block `{}`,
651 // or an unsafe expression `unsafe { e }`.
652 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
656 let prefix = block_prefix(context, self, shape)?;
657 let shape = shape.offset_left(last_line_width(&prefix))?;
659 let result = rewrite_block_with_visitor(context, &prefix, self, shape, true);
660 if let Some(ref result_str) = result {
661 if result_str.lines().count() <= 3 {
662 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
672 impl Rewrite for ast::Stmt {
673 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
674 skip_out_of_file_lines_range!(context, self.span());
676 let result = match self.node {
677 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
678 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
679 let suffix = if semicolon_for_stmt(context, self) {
685 let shape = shape.sub_width(suffix.len())?;
686 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
688 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
690 result.and_then(|res| recover_comment_removed(res, self.span(), context))
694 // Rewrite condition if the given expression has one.
695 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
697 ast::ExprKind::Match(ref cond, _) => {
699 let cond_shape = match context.config.indent_style() {
700 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
701 IndentStyle::Block => shape.offset_left(8)?,
703 cond.rewrite(context, cond_shape)
705 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
707 String::from("\n") + &shape.indent.block_only().to_string(context.config);
709 .rewrite_cond(context, shape, &alt_block_sep)
710 .and_then(|rw| Some(rw.0))
715 // Abstraction over control flow expressions
717 struct ControlFlow<'a> {
718 cond: Option<&'a ast::Expr>,
719 block: &'a ast::Block,
720 else_block: Option<&'a ast::Expr>,
721 label: Option<ast::SpannedIdent>,
722 pat: Option<&'a ast::Pat>,
726 allow_single_line: bool,
727 // True if this is an `if` expression in an `else if` :-( hacky
732 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
734 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
738 else_block.as_ref().map(|e| &**e),
739 expr_type == ExprType::SubExpression,
743 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
744 Some(ControlFlow::new_if(
748 else_block.as_ref().map(|e| &**e),
749 expr_type == ExprType::SubExpression,
754 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
755 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
757 ast::ExprKind::Loop(ref block, label) => {
758 Some(ControlFlow::new_loop(block, label, expr.span))
760 ast::ExprKind::While(ref cond, ref block, label) => {
761 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
763 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
764 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
770 impl<'a> ControlFlow<'a> {
773 pat: Option<&'a ast::Pat>,
774 block: &'a ast::Block,
775 else_block: Option<&'a ast::Expr>,
776 allow_single_line: bool,
779 ) -> ControlFlow<'a> {
783 else_block: else_block,
792 allow_single_line: allow_single_line,
793 nested_if: nested_if,
799 block: &'a ast::Block,
800 label: Option<ast::SpannedIdent>,
802 ) -> ControlFlow<'a> {
812 allow_single_line: false,
819 pat: Option<&'a ast::Pat>,
821 block: &'a ast::Block,
822 label: Option<ast::SpannedIdent>,
824 ) -> ControlFlow<'a> {
837 allow_single_line: false,
846 block: &'a ast::Block,
847 label: Option<ast::SpannedIdent>,
849 ) -> ControlFlow<'a> {
859 allow_single_line: false,
865 fn rewrite_single_line(
868 context: &RewriteContext,
870 ) -> Option<String> {
871 assert!(self.allow_single_line);
872 let else_block = self.else_block?;
873 let fixed_cost = self.keyword.len() + " { } else { }".len();
875 if let ast::ExprKind::Block(ref else_node) = else_block.node {
876 if !is_simple_block(self.block, context.codemap)
877 || !is_simple_block(else_node, context.codemap)
878 || pat_expr_str.contains('\n')
883 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
884 let expr = &self.block.stmts[0];
885 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
887 let new_width = new_width.checked_sub(if_str.len())?;
888 let else_expr = &else_node.stmts[0];
889 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
891 if if_str.contains('\n') || else_str.contains('\n') {
895 let result = format!(
896 "{} {} {{ {} }} else {{ {} }}",
897 self.keyword, pat_expr_str, if_str, else_str
900 if result.len() <= width {
909 impl<'a> ControlFlow<'a> {
912 context: &RewriteContext,
915 ) -> Option<(String, usize)> {
916 // Do not take the rhs overhead from the upper expressions into account
917 // when rewriting pattern.
918 let new_width = context
921 .checked_sub(shape.used_width())
923 let fresh_shape = Shape {
927 let constr_shape = if self.nested_if {
928 // We are part of an if-elseif-else chain. Our constraints are tightened.
929 // 7 = "} else " .len()
930 fresh_shape.offset_left(7)?
935 let label_string = rewrite_label(self.label);
936 // 1 = space after keyword.
937 let offset = self.keyword.len() + label_string.len() + 1;
939 let pat_expr_string = match self.cond {
940 Some(cond) => rewrite_pat_expr(
950 None => String::new(),
954 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
960 let one_line_budget = context
963 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
965 let force_newline_brace = (pat_expr_string.contains('\n')
966 || pat_expr_string.len() > one_line_budget)
967 && !last_line_extendable(&pat_expr_string);
969 // Try to format if-else on single line.
970 if self.allow_single_line
974 .single_line_if_else_max_width > 0
976 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
978 if let Some(cond_str) = trial {
983 .single_line_if_else_max_width
985 return Some((cond_str, 0));
990 let cond_span = if let Some(cond) = self.cond {
993 mk_sp(self.block.span.lo(), self.block.span.lo())
996 // `for event in event`
997 // Do not include label in the span.
998 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
999 let between_kwd_cond = mk_sp(
1002 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1003 self.pat.map_or(cond_span.lo(), |p| {
1004 if self.matcher.is_empty() {
1007 context.codemap.span_before(self.span, self.matcher.trim())
1012 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1014 let after_cond_comment =
1015 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1017 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1019 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1020 || force_newline_brace
1027 let used_width = if pat_expr_string.contains('\n') {
1028 last_line_width(&pat_expr_string)
1030 // 2 = spaces after keyword and condition.
1031 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1039 between_kwd_cond_comment.as_ref().map_or(
1040 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1048 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1055 impl<'a> Rewrite for ControlFlow<'a> {
1056 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1057 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1059 let alt_block_sep = String::from("\n") + &shape.indent.to_string(context.config);
1060 let (cond_str, used_width) = self.rewrite_cond(context, shape, &alt_block_sep)?;
1061 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1062 if used_width == 0 {
1063 return Some(cond_str);
1066 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1067 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1068 // we should avoid the single line case.
1069 let block_width = if self.else_block.is_some() || self.nested_if {
1074 let block_shape = Shape {
1078 let mut block_context = context.clone();
1079 block_context.is_if_else_block = self.else_block.is_some();
1081 rewrite_block_with_visitor(&block_context, "", self.block, block_shape, true)?;
1083 let mut result = format!("{}{}", cond_str, block_str);
1085 if let Some(else_block) = self.else_block {
1086 let shape = Shape::indented(shape.indent, context.config);
1087 let mut last_in_chain = false;
1088 let rewrite = match else_block.node {
1089 // If the else expression is another if-else expression, prevent it
1090 // from being formatted on a single line.
1091 // Note how we're passing the original shape, as the
1092 // cost of "else" should not cascade.
1093 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1094 ControlFlow::new_if(
1098 next_else_block.as_ref().map(|e| &**e),
1101 mk_sp(else_block.span.lo(), self.span.hi()),
1102 ).rewrite(context, shape)
1104 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1105 ControlFlow::new_if(
1109 next_else_block.as_ref().map(|e| &**e),
1112 mk_sp(else_block.span.lo(), self.span.hi()),
1113 ).rewrite(context, shape)
1116 last_in_chain = true;
1117 // When rewriting a block, the width is only used for single line
1118 // blocks, passing 1 lets us avoid that.
1119 let else_shape = Shape {
1120 width: min(1, shape.width),
1123 format_expr(else_block, ExprType::Statement, context, else_shape)
1127 let between_kwd_else_block = mk_sp(
1128 self.block.span.hi(),
1131 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1133 let between_kwd_else_block_comment =
1134 extract_comment(between_kwd_else_block, context, shape);
1136 let after_else = mk_sp(
1139 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1140 else_block.span.lo(),
1142 let after_else_comment = extract_comment(after_else, context, shape);
1144 let between_sep = match context.config.control_brace_style() {
1145 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1148 ControlBraceStyle::AlwaysSameLine => " ",
1150 let after_sep = match context.config.control_brace_style() {
1151 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1155 result.push_str(&format!(
1157 between_kwd_else_block_comment
1159 .map_or(between_sep, |s| &**s),
1160 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1162 result.push_str(&rewrite?);
1169 fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
1171 Some(ident) => Cow::from(format!("{}: ", ident.node)),
1172 None => Cow::from(""),
1176 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1177 match rewrite_missing_comment(span, shape, context) {
1178 Some(ref comment) if !comment.is_empty() => Some(format!(
1179 "\n{indent}{}\n{indent}",
1181 indent = shape.indent.to_string(context.config)
1187 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1188 let snippet = codemap.span_to_snippet(block.span).unwrap();
1189 contains_comment(&snippet)
1192 // Checks that a block contains no statements, an expression and no comments.
1193 // FIXME: incorrectly returns false when comment is contained completely within
1195 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1196 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1197 && !block_contains_comment(block, codemap))
1200 /// Checks whether a block contains at most one statement or expression, and no comments.
1201 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1202 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1205 /// Checks whether a block contains no statements, expressions, or comments.
1206 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1207 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1210 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1212 ast::StmtKind::Expr(..) => true,
1217 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1218 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1225 // A simple wrapper type against ast::Arm. Used inside write_list().
1226 struct ArmWrapper<'a> {
1227 pub arm: &'a ast::Arm,
1228 // True if the arm is the last one in match expression. Used to decide on whether we should add
1229 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1233 impl<'a> ArmWrapper<'a> {
1234 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1235 ArmWrapper { arm, is_last }
1239 impl<'a> Rewrite for ArmWrapper<'a> {
1240 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1241 rewrite_match_arm(context, self.arm, shape, self.is_last)
1246 context: &RewriteContext,
1251 attrs: &[ast::Attribute],
1252 ) -> Option<String> {
1253 // Do not take the rhs overhead from the upper expressions into account
1254 // when rewriting match condition.
1255 let cond_shape = Shape {
1256 width: context.budget(shape.used_width()),
1260 let cond_shape = match context.config.indent_style() {
1261 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1262 IndentStyle::Block => cond_shape.offset_left(6)?,
1264 let cond_str = cond.rewrite(context, cond_shape)?;
1265 let alt_block_sep = String::from("\n") + &shape.indent.to_string(context.config);
1266 let block_sep = match context.config.control_brace_style() {
1267 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1268 _ if last_line_extendable(&cond_str) => " ",
1270 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1274 let nested_indent_str = shape
1276 .block_indent(context.config)
1277 .to_string(context.config);
1278 // Inner attributes.
1279 let inner_attrs = &inner_attributes(attrs);
1280 let inner_attrs_str = if inner_attrs.is_empty() {
1284 .rewrite(context, shape)
1285 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1288 let open_brace_pos = if inner_attrs.is_empty() {
1289 let hi = if arms.is_empty() {
1294 context.codemap.span_after(mk_sp(cond.span.hi(), hi), "{")
1296 inner_attrs[inner_attrs.len() - 1].span().hi()
1299 if arms.is_empty() {
1300 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1301 if snippet.trim().is_empty() {
1302 Some(format!("match {} {{}}", cond_str))
1304 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1305 Some(context.snippet(span).to_owned())
1309 "match {}{}{{\n{}{}{}\n{}}}",
1314 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1315 shape.indent.to_string(context.config),
1320 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1321 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1323 } else if config.match_block_trailing_comma() {
1325 } else if let ast::ExprKind::Block(ref block) = body.node {
1326 if let ast::BlockCheckMode::Default = block.rules {
1336 fn rewrite_match_arms(
1337 context: &RewriteContext,
1341 open_brace_pos: BytePos,
1342 ) -> Option<String> {
1343 let arm_shape = shape
1344 .block_indent(context.config.tab_spaces())
1345 .with_max_width(context.config);
1347 let arm_len = arms.len();
1348 let is_last_iter = repeat(false)
1349 .take(arm_len.checked_sub(1).unwrap_or(0))
1350 .chain(repeat(true));
1351 let items = itemize_list(
1355 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1358 |arm| arm.arm.span().lo(),
1359 |arm| arm.arm.span().hi(),
1360 |arm| arm.rewrite(context, arm_shape),
1365 let arms_vec: Vec<_> = items.collect();
1366 let fmt = ListFormatting {
1367 tactic: DefinitiveListTactic::Vertical,
1368 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1370 trailing_separator: SeparatorTactic::Never,
1371 separator_place: SeparatorPlace::Back,
1373 ends_with_newline: true,
1374 preserve_newline: true,
1375 config: context.config,
1378 write_list(&arms_vec, &fmt)
1381 fn rewrite_match_arm(
1382 context: &RewriteContext,
1386 ) -> Option<String> {
1387 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1388 if contains_skip(&arm.attrs) {
1389 let (_, body) = flatten_arm_body(context, &arm.body);
1390 // `arm.span()` does not include trailing comma, add it manually.
1391 return Some(format!(
1393 context.snippet(arm.span()),
1394 arm_comma(context.config, body, is_last),
1397 let missing_span = mk_sp(
1398 arm.attrs[arm.attrs.len() - 1].span.hi(),
1399 arm.pats[0].span.lo(),
1401 (missing_span, arm.attrs.rewrite(context, shape)?)
1403 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1406 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1407 combine_strs_with_missing_comments(
1421 arm.guard.is_some(),
1426 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
1430 /// - `&[single-line, ntp]`
1433 /// - `[small, ntp]`
1434 /// - unary tuple constructor `([small, ntp])`
1436 fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
1437 // We also require that the pattern is reasonably 'small' with its literal width.
1438 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
1441 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
1443 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
1444 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
1445 ast::PatKind::Struct(..)
1446 | ast::PatKind::Mac(..)
1447 | ast::PatKind::Slice(..)
1448 | ast::PatKind::Path(..)
1449 | ast::PatKind::Range(..) => false,
1450 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
1451 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
1452 path.segments.len() <= 1 && subpats.len() <= 1
1454 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) => is_short_pattern_inner(&*p),
1458 fn rewrite_match_pattern(
1459 context: &RewriteContext,
1460 pats: &[ptr::P<ast::Pat>],
1461 guard: &Option<ptr::P<ast::Expr>>,
1463 ) -> Option<String> {
1466 let pat_shape = shape.sub_width(5)?;
1468 let pat_strs = pats.iter()
1469 .map(|p| p.rewrite(context, pat_shape))
1470 .collect::<Option<Vec<_>>>()?;
1472 let use_mixed_layout = pats.iter()
1473 .zip(pat_strs.iter())
1474 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1475 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1476 let tactic = if use_mixed_layout {
1477 DefinitiveListTactic::Mixed
1481 ListTactic::HorizontalVertical,
1482 Separator::VerticalBar,
1486 let fmt = ListFormatting {
1489 trailing_separator: SeparatorTactic::Never,
1490 separator_place: context.config.binop_separator(),
1492 ends_with_newline: false,
1493 preserve_newline: false,
1494 config: context.config,
1496 let pats_str = write_list(&items, &fmt)?;
1499 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1501 Some(format!("{}{}", pats_str, guard_str))
1505 // @extend: true if the arm body can be put next to `=>`
1506 // @body: flattened body, if the body is block with a single expression
1507 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1509 ast::ExprKind::Block(ref block)
1510 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1512 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1514 !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
1522 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
1528 fn rewrite_match_body(
1529 context: &RewriteContext,
1530 body: &ptr::P<ast::Expr>,
1535 ) -> Option<String> {
1536 let (extend, body) = flatten_arm_body(context, body);
1537 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1538 (true, is_empty_block(block, context.codemap))
1543 let comma = arm_comma(context.config, body, is_last);
1544 let alt_block_sep = String::from("\n") + &shape.indent.to_string(context.config);
1545 let alt_block_sep = alt_block_sep.as_str();
1547 let combine_orig_body = |body_str: &str| {
1548 let block_sep = match context.config.control_brace_style() {
1549 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1553 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1556 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1557 let next_line_indent = if !is_block || is_empty_block {
1558 shape.indent.block_indent(context.config)
1562 let combine_next_line_body = |body_str: &str| {
1564 return Some(format!(
1567 next_line_indent.to_string(context.config),
1572 let indent_str = shape.indent.to_string(context.config);
1573 let nested_indent_str = next_line_indent.to_string(context.config);
1574 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
1575 let comma = if context.config.match_block_trailing_comma() {
1580 ("{", format!("\n{}}}{}", indent_str, comma))
1582 ("", String::from(","))
1585 let block_sep = match context.config.control_brace_style() {
1586 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1587 _ if body_prefix.is_empty() => "\n".to_owned(),
1588 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1589 _ => format!(" {}\n", body_prefix),
1590 } + &nested_indent_str;
1594 pats_str, block_sep, body_str, body_suffix
1598 // Let's try and get the arm body on the same line as the condition.
1600 let orig_body_shape = shape
1601 .offset_left(extra_offset(pats_str, shape) + 4)
1602 .and_then(|shape| shape.sub_width(comma.len()));
1603 let orig_body = if let Some(body_shape) = orig_body_shape {
1604 let rewrite = nop_block_collapse(
1605 format_expr(body, ExprType::Statement, context, body_shape),
1611 if !forbid_same_line
1613 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1615 return combine_orig_body(body_str);
1622 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1624 // Try putting body on the next line and see if it looks better.
1625 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1626 let next_line_body = nop_block_collapse(
1627 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1628 next_line_body_shape.width,
1630 match (orig_body, next_line_body) {
1631 (Some(ref orig_str), Some(ref next_line_str))
1632 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1634 combine_next_line_body(next_line_str)
1636 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1637 combine_orig_body(orig_str)
1639 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1640 combine_next_line_body(next_line_str)
1642 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1643 (None, None) => None,
1644 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1648 // The `if ...` guard on a match arm.
1650 context: &RewriteContext,
1651 guard: &Option<ptr::P<ast::Expr>>,
1653 // The amount of space used up on this line for the pattern in
1654 // the arm (excludes offset).
1655 pattern_width: usize,
1656 ) -> Option<String> {
1657 if let Some(ref guard) = *guard {
1658 // First try to fit the guard string on the same line as the pattern.
1659 // 4 = ` if `, 5 = ` => {`
1660 let cond_shape = shape
1661 .offset_left(pattern_width + 4)
1662 .and_then(|s| s.sub_width(5));
1663 if let Some(cond_shape) = cond_shape {
1664 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1665 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1666 return Some(format!(" if {}", cond_str));
1671 // Not enough space to put the guard after the pattern, try a newline.
1672 // 3 = `if `, 5 = ` => {`
1673 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1675 .and_then(|s| s.sub_width(5));
1676 if let Some(cond_shape) = cond_shape {
1677 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1678 return Some(format!(
1680 cond_shape.indent.to_string(context.config),
1692 fn rewrite_pat_expr(
1693 context: &RewriteContext,
1694 pat: Option<&ast::Pat>,
1697 // Connecting piece between pattern and expression,
1698 // *without* trailing space.
1703 ) -> Option<String> {
1704 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1705 let cond_shape = shape.offset_left(offset)?;
1706 if let Some(pat) = pat {
1707 let matcher = if matcher.is_empty() {
1710 format!("{} ", matcher)
1712 let pat_shape = cond_shape
1713 .offset_left(matcher.len())?
1714 .sub_width(connector.len())?;
1715 let pat_string = pat.rewrite(context, pat_shape)?;
1716 let result = format!("{}{}{}", matcher, pat_string, connector);
1717 return rewrite_assign_rhs(context, result, expr, cond_shape);
1720 let expr_rw = expr.rewrite(context, cond_shape);
1721 // The expression may (partially) fit on the current line.
1722 // We do not allow splitting between `if` and condition.
1723 if keyword == "if" || expr_rw.is_some() {
1727 // The expression won't fit on the current line, jump to next.
1728 let nested_shape = shape
1729 .block_indent(context.config.tab_spaces())
1730 .with_max_width(context.config);
1731 let nested_indent_str = nested_shape.indent.to_string(context.config);
1732 expr.rewrite(context, nested_shape)
1733 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1736 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
1738 // We do not allow `if` to stay on the same line, since we could easily mistake
1739 // `pat => if cond { ... }` and `pat if cond => { ... }`.
1740 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
1741 ast::ExprKind::ForLoop(..)
1742 | ast::ExprKind::Loop(..)
1743 | ast::ExprKind::While(..)
1744 | ast::ExprKind::WhileLet(..)
1745 | ast::ExprKind::Match(..)
1746 | ast::ExprKind::Block(..)
1747 | ast::ExprKind::Closure(..)
1748 | ast::ExprKind::Array(..)
1749 | ast::ExprKind::Call(..)
1750 | ast::ExprKind::MethodCall(..)
1751 | ast::ExprKind::Mac(..)
1752 | ast::ExprKind::Struct(..)
1753 | ast::ExprKind::Tup(..) => true,
1754 ast::ExprKind::AddrOf(_, ref expr)
1755 | ast::ExprKind::Box(ref expr)
1756 | ast::ExprKind::Try(ref expr)
1757 | ast::ExprKind::Unary(_, ref expr)
1758 | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
1763 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1765 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1767 context.snippet(l.span).to_owned(),
1768 context.config.max_width(),
1774 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1775 let string_lit = context.snippet(span);
1777 if !context.config.format_strings() {
1782 .all(|line| line.ends_with('\\'))
1784 let new_indent = shape.visual_indent(1).indent;
1785 let indented_string_lit = String::from(
1791 new_indent.to_string(context.config),
1795 .collect::<Vec<_>>()
1799 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1801 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1805 // Remove the quote characters.
1806 let str_lit = &string_lit[1..string_lit.len() - 1];
1810 &StringFormat::new(shape.visual_indent(0), context.config),
1815 const FORMAT_LIKE_WHITELIST: &[&str] = &[
1816 // From the Rust Standard Library.
1825 // From the `log` crate.
1832 const WRITE_LIKE_WHITELIST: &[&str] = &["assert!", "write!", "writeln!"];
1834 pub fn rewrite_call(
1835 context: &RewriteContext,
1837 args: &[ptr::P<ast::Expr>],
1840 ) -> Option<String> {
1841 let force_trailing_comma = if context.inside_macro {
1842 span_ends_with_comma(context, span)
1849 &ptr_vec_to_ref_vec(args),
1852 context.config.width_heuristics().fn_call_width,
1853 force_trailing_comma,
1857 pub fn rewrite_call_inner<'a, T>(
1858 context: &RewriteContext,
1863 args_max_width: usize,
1864 force_trailing_comma: bool,
1867 T: Rewrite + Spanned + ToExpr + 'a,
1869 // 2 = `( `, 1 = `(`
1870 let paren_overhead = if context.config.spaces_within_parens_and_brackets() {
1875 let used_width = extra_offset(callee_str, shape);
1876 let one_line_width = shape.width.checked_sub(used_width + 2 * paren_overhead)?;
1879 let one_line_shape = shape
1880 .offset_left(last_line_width(callee_str) + 1)?
1882 let nested_shape = shape_from_indent_style(
1885 used_width + 2 * paren_overhead,
1886 used_width + paren_overhead,
1889 let span_lo = context.codemap.span_after(span, "(");
1890 let args_span = mk_sp(span_lo, span.hi());
1892 let (extendable, list_str) = rewrite_call_args(
1900 force_trailing_comma,
1904 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
1905 let mut new_context = context.clone();
1906 new_context.use_block = true;
1907 return rewrite_call_inner(
1914 force_trailing_comma,
1918 let args_shape = shape.sub_width(last_line_width(callee_str))?;
1922 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
1926 fn need_block_indent(s: &str, shape: Shape) -> bool {
1927 s.lines().skip(1).any(|s| {
1928 s.find(|c| !char::is_whitespace(c))
1929 .map_or(false, |w| w + 1 < shape.indent.width())
1933 fn rewrite_call_args<'a, T>(
1934 context: &RewriteContext,
1937 one_line_shape: Shape,
1938 nested_shape: Shape,
1939 one_line_width: usize,
1940 args_max_width: usize,
1941 force_trailing_comma: bool,
1943 ) -> Option<(bool, String)>
1945 T: Rewrite + Spanned + ToExpr + 'a,
1947 let items = itemize_list(
1952 |item| item.span().lo(),
1953 |item| item.span().hi(),
1954 |item| item.rewrite(context, nested_shape),
1959 let mut item_vec: Vec<_> = items.collect();
1961 // Try letting the last argument overflow to the next line with block
1962 // indentation. If its first line fits on one line with the other arguments,
1963 // we format the function arguments horizontally.
1964 let tactic = try_overflow_last_arg(
1975 let fmt = ListFormatting {
1978 trailing_separator: if force_trailing_comma {
1979 SeparatorTactic::Always
1980 } else if context.inside_macro || !context.use_block_indent() {
1981 SeparatorTactic::Never
1983 context.config.trailing_comma()
1985 separator_place: SeparatorPlace::Back,
1986 shape: nested_shape,
1987 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
1988 preserve_newline: false,
1989 config: context.config,
1992 write_list(&item_vec, &fmt)
1993 .map(|args_str| (tactic == DefinitiveListTactic::Horizontal, args_str))
1996 fn try_overflow_last_arg<'a, T>(
1997 context: &RewriteContext,
1998 item_vec: &mut Vec<ListItem>,
2000 one_line_shape: Shape,
2001 nested_shape: Shape,
2002 one_line_width: usize,
2003 args_max_width: usize,
2005 ) -> DefinitiveListTactic
2007 T: Rewrite + Spanned + ToExpr + 'a,
2010 let combine_arg_with_callee =
2011 callee_str.len() + 1 <= context.config.tab_spaces() && args.len() == 1;
2012 let overflow_last = combine_arg_with_callee || can_be_overflowed(context, args);
2014 // Replace the last item with its first line to see if it fits with
2016 let placeholder = if overflow_last {
2017 let mut context = context.clone();
2018 if !combine_arg_with_callee {
2019 if let Some(expr) = args[args.len() - 1].to_expr() {
2020 if let ast::ExprKind::MethodCall(..) = expr.node {
2021 context.force_one_line_chain = true;
2025 last_arg_shape(args, item_vec, one_line_shape, args_max_width).and_then(|arg_shape| {
2026 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2032 let mut tactic = definitive_tactic(
2034 ListTactic::LimitedHorizontalVertical(args_max_width),
2039 // Replace the stub with the full overflowing last argument if the rewrite
2040 // succeeded and its first line fits with the other arguments.
2041 match (overflow_last, tactic, placeholder) {
2042 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2043 item_vec[args.len() - 1].item = placeholder;
2045 _ if args.len() >= 1 => {
2046 item_vec[args.len() - 1].item = args.last()
2047 .and_then(|last_arg| last_arg.rewrite(context, nested_shape));
2049 let default_tactic = || {
2052 ListTactic::LimitedHorizontalVertical(args_max_width),
2058 // Use horizontal layout for a function with a single argument as long as
2059 // everything fits in a single line.
2061 && args_max_width != 0 // Vertical layout is forced.
2062 && !item_vec[0].has_comment()
2063 && !item_vec[0].inner_as_ref().contains('\n')
2064 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
2066 tactic = DefinitiveListTactic::Horizontal;
2068 tactic = default_tactic();
2070 // For special-case macros, we may want to use different tactics.
2071 let maybe_args_offset = maybe_get_args_offset(callee_str, args);
2073 if tactic == DefinitiveListTactic::Vertical && maybe_args_offset.is_some() {
2074 let args_offset = maybe_args_offset.unwrap();
2075 let args_tactic = definitive_tactic(
2076 &item_vec[args_offset..],
2077 ListTactic::HorizontalVertical,
2082 // Every argument is simple and fits on a single line.
2083 if args_tactic == DefinitiveListTactic::Horizontal {
2084 tactic = if args_offset == 1 {
2085 DefinitiveListTactic::FormatCall
2087 DefinitiveListTactic::WriteCall
2099 fn is_simple_arg(expr: &ast::Expr) -> bool {
2101 ast::ExprKind::Lit(..) => true,
2102 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
2103 ast::ExprKind::AddrOf(_, ref expr)
2104 | ast::ExprKind::Box(ref expr)
2105 | ast::ExprKind::Cast(ref expr, _)
2106 | ast::ExprKind::Field(ref expr, _)
2107 | ast::ExprKind::Try(ref expr)
2108 | ast::ExprKind::TupField(ref expr, _)
2109 | ast::ExprKind::Unary(_, ref expr) => is_simple_arg(expr),
2110 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
2111 is_simple_arg(lhs) && is_simple_arg(rhs)
2117 fn is_every_args_simple<T: ToExpr>(lists: &[&T]) -> bool {
2120 .all(|arg| arg.to_expr().map_or(false, is_simple_arg))
2123 /// In case special-case style is required, returns an offset from which we start horizontal layout.
2124 fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<usize> {
2125 if FORMAT_LIKE_WHITELIST.iter().any(|s| *s == callee_str) && args.len() >= 1
2126 && is_every_args_simple(args)
2129 } else if WRITE_LIKE_WHITELIST.iter().any(|s| *s == callee_str) && args.len() >= 2
2130 && is_every_args_simple(args)
2138 /// Returns a shape for the last argument which is going to be overflowed.
2139 fn last_arg_shape<T>(
2143 args_max_width: usize,
2146 T: Rewrite + Spanned + ToExpr,
2148 let is_nested_call = lists
2151 .and_then(|item| item.to_expr())
2152 .map_or(false, is_nested_call);
2153 if items.len() == 1 && !is_nested_call {
2156 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
2158 acc + 2 + i.inner_as_ref().len()
2161 width: min(args_max_width, shape.width),
2163 }.offset_left(offset)
2166 fn rewrite_last_arg_with_overflow<'a, T>(
2167 context: &RewriteContext,
2169 last_item: &mut ListItem,
2173 T: Rewrite + Spanned + ToExpr + 'a,
2175 let last_arg = args[args.len() - 1];
2176 let rewrite = if let Some(expr) = last_arg.to_expr() {
2178 // When overflowing the closure which consists of a single control flow expression,
2179 // force to use block if its condition uses multi line.
2180 ast::ExprKind::Closure(..) => {
2181 // If the argument consists of multiple closures, we do not overflow
2182 // the last closure.
2183 if closures::args_have_many_closure(args) {
2186 closures::rewrite_last_closure(context, expr, shape)
2189 _ => expr.rewrite(context, shape),
2192 last_arg.rewrite(context, shape)
2195 if let Some(rewrite) = rewrite {
2196 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2197 last_item.item = rewrite_first_line;
2204 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2206 T: Rewrite + Spanned + ToExpr + 'a,
2209 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2212 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2214 ast::ExprKind::Match(..) => {
2215 (context.use_block_indent() && args_len == 1)
2216 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
2218 ast::ExprKind::If(..)
2219 | ast::ExprKind::IfLet(..)
2220 | ast::ExprKind::ForLoop(..)
2221 | ast::ExprKind::Loop(..)
2222 | ast::ExprKind::While(..)
2223 | ast::ExprKind::WhileLet(..) => {
2224 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2226 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2227 context.use_block_indent()
2228 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
2230 ast::ExprKind::Array(..)
2231 | ast::ExprKind::Call(..)
2232 | ast::ExprKind::Mac(..)
2233 | ast::ExprKind::MethodCall(..)
2234 | ast::ExprKind::Struct(..)
2235 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2236 ast::ExprKind::AddrOf(_, ref expr)
2237 | ast::ExprKind::Box(ref expr)
2238 | ast::ExprKind::Try(ref expr)
2239 | ast::ExprKind::Unary(_, ref expr)
2240 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2245 fn is_nested_call(expr: &ast::Expr) -> bool {
2247 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
2248 ast::ExprKind::AddrOf(_, ref expr)
2249 | ast::ExprKind::Box(ref expr)
2250 | ast::ExprKind::Try(ref expr)
2251 | ast::ExprKind::Unary(_, ref expr)
2252 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
2257 pub fn wrap_args_with_parens(
2258 context: &RewriteContext,
2260 is_extendable: bool,
2262 nested_shape: Shape,
2264 if !context.use_block_indent()
2265 || (context.inside_macro && !args_str.contains('\n')
2266 && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2268 if context.config.spaces_within_parens_and_brackets() && !args_str.is_empty() {
2269 format!("( {} )", args_str)
2271 format!("({})", args_str)
2276 nested_shape.indent.to_string(context.config),
2278 shape.block().indent.to_string(context.config)
2283 /// Return true if a function call or a method call represented by the given span ends with a
2284 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2285 /// comma from macro can potentially break the code.
2286 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2287 let mut encountered_closing_paren = false;
2288 for c in context.snippet(span).chars().rev() {
2291 ')' => if encountered_closing_paren {
2294 encountered_closing_paren = true;
2296 _ if c.is_whitespace() => continue,
2303 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2304 debug!("rewrite_paren, shape: {:?}", shape);
2305 let total_paren_overhead = paren_overhead(context);
2306 let paren_overhead = total_paren_overhead / 2;
2307 let sub_shape = shape
2308 .offset_left(paren_overhead)
2309 .and_then(|s| s.sub_width(paren_overhead))?;
2311 let paren_wrapper = |s: &str| {
2312 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2313 format!("( {} )", s)
2319 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2320 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2322 if subexpr_str.contains('\n')
2323 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2325 Some(paren_wrapper(&subexpr_str))
2334 context: &RewriteContext,
2336 ) -> Option<String> {
2337 let expr_str = expr.rewrite(context, shape)?;
2339 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2345 let offset = last_line_width(&expr_str) + lbr.len();
2346 let rhs_overhead = shape.rhs_overhead(context.config);
2347 let index_shape = if expr_str.contains('\n') {
2348 Shape::legacy(context.config.max_width(), shape.indent)
2349 .offset_left(offset)
2350 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2352 shape.visual_indent(offset).sub_width(offset + rbr.len())
2354 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2356 // Return if index fits in a single line.
2357 match orig_index_rw {
2358 Some(ref index_str) if !index_str.contains('\n') => {
2359 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2364 // Try putting index on the next line and see if it fits in a single line.
2365 let indent = shape.indent.block_indent(context.config);
2366 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2367 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2368 let new_index_rw = index.rewrite(context, index_shape);
2369 match (orig_index_rw, new_index_rw) {
2370 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2373 indent.to_string(context.config),
2378 (None, Some(ref new_index_str)) => Some(format!(
2381 indent.to_string(context.config),
2386 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2391 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2396 fields.iter().all(|field| !field.is_shorthand)
2399 fn rewrite_struct_lit<'a>(
2400 context: &RewriteContext,
2402 fields: &'a [ast::Field],
2403 base: Option<&'a ast::Expr>,
2406 ) -> Option<String> {
2407 debug!("rewrite_struct_lit: shape {:?}", shape);
2409 enum StructLitField<'a> {
2410 Regular(&'a ast::Field),
2411 Base(&'a ast::Expr),
2415 let path_shape = shape.sub_width(2)?;
2416 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2418 if fields.is_empty() && base.is_none() {
2419 return Some(format!("{} {{}}", path_str));
2422 // Foo { a: Foo } - indent is +3, width is -5.
2423 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2425 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2426 let body_lo = context.codemap.span_after(span, "{");
2427 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2428 && context.config.struct_field_align_threshold() > 0
2430 rewrite_with_alignment(
2434 mk_sp(body_lo, span.hi()),
2438 let field_iter = fields
2440 .map(StructLitField::Regular)
2441 .chain(base.into_iter().map(StructLitField::Base));
2443 let span_lo = |item: &StructLitField| match *item {
2444 StructLitField::Regular(field) => field.span().lo(),
2445 StructLitField::Base(expr) => {
2446 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2447 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2448 let pos = snippet.find_uncommented("..").unwrap();
2449 last_field_hi + BytePos(pos as u32)
2452 let span_hi = |item: &StructLitField| match *item {
2453 StructLitField::Regular(field) => field.span().hi(),
2454 StructLitField::Base(expr) => expr.span.hi(),
2456 let rewrite = |item: &StructLitField| match *item {
2457 StructLitField::Regular(field) => {
2458 // The 1 taken from the v_budget is for the comma.
2459 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2461 StructLitField::Base(expr) => {
2463 expr.rewrite(context, v_shape.offset_left(2)?)
2464 .map(|s| format!("..{}", s))
2468 let items = itemize_list(
2480 let item_vec = items.collect::<Vec<_>>();
2482 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2483 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2484 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2486 write_list(&item_vec, &fmt)?
2489 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2490 Some(format!("{} {{{}}}", path_str, fields_str))
2492 // FIXME if context.config.indent_style() == Visual, but we run out
2493 // of space, we should fall back to BlockIndent.
2496 pub fn wrap_struct_field(
2497 context: &RewriteContext,
2500 nested_shape: Shape,
2501 one_line_width: usize,
2503 if context.config.indent_style() == IndentStyle::Block
2504 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
2505 || fields_str.len() > one_line_width)
2509 nested_shape.indent.to_string(context.config),
2511 shape.indent.to_string(context.config)
2514 // One liner or visual indent.
2515 format!(" {} ", fields_str)
2519 pub fn struct_lit_field_separator(config: &Config) -> &str {
2520 colon_spaces(config.space_before_colon(), config.space_after_colon())
2523 pub fn rewrite_field(
2524 context: &RewriteContext,
2527 prefix_max_width: usize,
2528 ) -> Option<String> {
2529 if contains_skip(&field.attrs) {
2530 return Some(context.snippet(field.span()).to_owned());
2532 let name = &field.ident.node.to_string();
2533 if field.is_shorthand {
2534 Some(name.to_string())
2536 let mut separator = String::from(struct_lit_field_separator(context.config));
2537 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2538 separator.push(' ');
2540 let overhead = name.len() + separator.len();
2541 let expr_shape = shape.offset_left(overhead)?;
2542 let expr = field.expr.rewrite(context, expr_shape);
2544 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2545 if !attrs_str.is_empty() {
2546 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2550 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2552 let expr_offset = shape.indent.block_indent(context.config);
2555 .rewrite(context, Shape::indented(expr_offset, context.config));
2561 expr_offset.to_string(context.config),
2570 fn shape_from_indent_style(
2571 context: &RewriteContext,
2575 ) -> Option<Shape> {
2576 if context.use_block_indent() {
2580 .block_indent(context.config.tab_spaces())
2581 .with_max_width(context.config)
2584 shape.visual_indent(offset).sub_width(overhead)
2588 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2589 context: &RewriteContext,
2595 T: Rewrite + Spanned + ToExpr + 'a,
2597 let mut items = items.iter();
2598 // In case of length 1, need a trailing comma
2599 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2600 if items.len() == 1 {
2602 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2606 .rewrite(context, nested_shape)
2608 if context.config.spaces_within_parens_and_brackets() {
2609 format!("( {}, )", s)
2616 let list_lo = context.codemap.span_after(span, "(");
2617 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2618 let items = itemize_list(
2623 |item| item.span().lo(),
2624 |item| item.span().hi(),
2625 |item| item.rewrite(context, nested_shape),
2627 span.hi() - BytePos(1),
2630 let item_vec: Vec<_> = items.collect();
2631 let tactic = definitive_tactic(
2633 ListTactic::HorizontalVertical,
2637 let fmt = ListFormatting {
2640 trailing_separator: SeparatorTactic::Never,
2641 separator_place: SeparatorPlace::Back,
2643 ends_with_newline: false,
2644 preserve_newline: false,
2645 config: context.config,
2647 let list_str = write_list(&item_vec, &fmt)?;
2649 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2650 Some(format!("( {} )", list_str))
2652 Some(format!("({})", list_str))
2656 pub fn rewrite_tuple<'a, T>(
2657 context: &RewriteContext,
2663 T: Rewrite + Spanned + ToExpr + 'a,
2665 debug!("rewrite_tuple {:?}", shape);
2666 if context.use_block_indent() {
2667 // We use the same rule as function calls for rewriting tuples.
2668 let force_trailing_comma = if context.inside_macro {
2669 span_ends_with_comma(context, span)
2679 context.config.width_heuristics().fn_call_width,
2680 force_trailing_comma,
2683 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2687 pub fn rewrite_unary_prefix<R: Rewrite>(
2688 context: &RewriteContext,
2692 ) -> Option<String> {
2694 .rewrite(context, shape.offset_left(prefix.len())?)
2695 .map(|r| format!("{}{}", prefix, r))
2698 // FIXME: this is probably not correct for multi-line Rewrites. we should
2699 // subtract suffix.len() from the last line budget, not the first!
2700 pub fn rewrite_unary_suffix<R: Rewrite>(
2701 context: &RewriteContext,
2705 ) -> Option<String> {
2707 .rewrite(context, shape.sub_width(suffix.len())?)
2714 fn rewrite_unary_op(
2715 context: &RewriteContext,
2719 ) -> Option<String> {
2720 // For some reason, an UnOp is not spanned like BinOp!
2721 let operator_str = match *op {
2722 ast::UnOp::Deref => "*",
2723 ast::UnOp::Not => "!",
2724 ast::UnOp::Neg => "-",
2726 rewrite_unary_prefix(context, operator_str, expr, shape)
2729 fn rewrite_assignment(
2730 context: &RewriteContext,
2733 op: Option<&ast::BinOp>,
2735 ) -> Option<String> {
2736 let operator_str = match op {
2737 Some(op) => context.snippet(op.span),
2741 // 1 = space between lhs and operator.
2742 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2743 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2745 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2748 // The left hand side must contain everything up to, and including, the
2749 // assignment operator.
2750 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2751 context: &RewriteContext,
2755 ) -> Option<String> {
2756 let lhs = lhs.into();
2757 let last_line_width = last_line_width(&lhs)
2758 .checked_sub(if lhs.contains('\n') {
2759 shape.indent.width()
2764 // 1 = space between operator and rhs.
2765 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2767 offset: shape.offset + last_line_width + 1,
2770 let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2774 pub fn choose_rhs<R: Rewrite>(
2775 context: &RewriteContext,
2778 orig_rhs: Option<String>,
2779 ) -> Option<String> {
2781 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2782 Some(format!(" {}", new_str))
2785 // Expression did not fit on the same line as the identifier.
2786 // Try splitting the line and see if that works better.
2788 Shape::indented(shape.indent.block_indent(context.config), context.config)
2789 .sub_width(shape.rhs_overhead(context.config))?;
2790 let new_rhs = expr.rewrite(context, new_shape);
2791 let new_indent_str = &new_shape.indent.to_string(context.config);
2793 match (orig_rhs, new_rhs) {
2794 (Some(ref orig_rhs), Some(ref new_rhs))
2795 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2798 Some(format!(" {}", orig_rhs))
2800 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2801 Some(format!("\n{}{}", new_indent_str, new_rhs))
2803 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2804 (None, None) => None,
2805 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2811 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2812 use utils::count_newlines;
2813 !next_line_rhs.contains('\n') || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2816 fn rewrite_expr_addrof(
2817 context: &RewriteContext,
2818 mutability: ast::Mutability,
2821 ) -> Option<String> {
2822 let operator_str = match mutability {
2823 ast::Mutability::Immutable => "&",
2824 ast::Mutability::Mutable => "&mut ",
2826 rewrite_unary_prefix(context, operator_str, expr, shape)
2830 fn to_expr(&self) -> Option<&ast::Expr>;
2831 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2834 impl ToExpr for ast::Expr {
2835 fn to_expr(&self) -> Option<&ast::Expr> {
2839 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2840 can_be_overflowed_expr(context, self, len)
2844 impl ToExpr for ast::Ty {
2845 fn to_expr(&self) -> Option<&ast::Expr> {
2849 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2850 can_be_overflowed_type(context, self, len)
2854 impl<'a> ToExpr for TuplePatField<'a> {
2855 fn to_expr(&self) -> Option<&ast::Expr> {
2859 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2860 can_be_overflowed_pat(context, self, len)
2864 impl<'a> ToExpr for ast::StructField {
2865 fn to_expr(&self) -> Option<&ast::Expr> {
2869 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2874 impl<'a> ToExpr for MacroArg {
2875 fn to_expr(&self) -> Option<&ast::Expr> {
2877 MacroArg::Expr(ref expr) => Some(expr),
2882 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2884 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2885 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2886 MacroArg::Pat(..) => false,