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, CharClasses, 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};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
33 use string::{rewrite_string, StringFormat};
34 use types::{can_be_overflowed_type, rewrite_path, PathContext};
35 use utils::{colon_spaces, contains_skip, count_newlines, extra_offset, first_line_width,
36 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
37 paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, trimmed_last_line_width,
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
42 impl Rewrite for ast::Expr {
43 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44 format_expr(self, ExprType::SubExpression, context, shape)
48 #[derive(Copy, Clone, PartialEq)]
57 context: &RewriteContext,
60 skip_out_of_file_lines_range!(context, expr.span);
62 if contains_skip(&*expr.attrs) {
63 return Some(context.snippet(expr.span()).to_owned());
66 let expr_rw = match expr.node {
67 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
68 &ptr_vec_to_ref_vec(expr_vec),
70 context.snippet_provider.span_after(expr.span, "["),
77 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
78 ast::ExprKind::Call(ref callee, ref args) => {
79 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
80 let callee_str = callee.rewrite(context, shape)?;
81 rewrite_call(context, &callee_str, args, inner_span, shape)
83 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
84 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
85 // FIXME: format comments between operands and operator
89 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
92 context.config.binop_separator(),
95 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
96 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
100 base.as_ref().map(|e| &**e),
104 ast::ExprKind::Tup(ref items) => {
105 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
107 ast::ExprKind::If(..)
108 | ast::ExprKind::IfLet(..)
109 | ast::ExprKind::ForLoop(..)
110 | ast::ExprKind::Loop(..)
111 | ast::ExprKind::While(..)
112 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
113 .and_then(|control_flow| control_flow.rewrite(context, shape)),
114 ast::ExprKind::Block(ref block) => {
116 ExprType::Statement => {
117 if is_unsafe_block(block) {
118 rewrite_block(block, Some(&expr.attrs), context, shape)
119 } else if let rw @ Some(_) =
120 rewrite_empty_block(context, block, Some(&expr.attrs), "", shape)
122 // Rewrite block without trying to put it in a single line.
125 let prefix = block_prefix(context, block, shape)?;
126 rewrite_block_with_visitor(
136 ExprType::SubExpression => rewrite_block(block, Some(&expr.attrs), context, shape),
139 ast::ExprKind::Match(ref cond, ref arms) => {
140 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
142 ast::ExprKind::Path(ref qself, ref path) => {
143 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
145 ast::ExprKind::Assign(ref lhs, ref rhs) => {
146 rewrite_assignment(context, lhs, rhs, None, shape)
148 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
149 rewrite_assignment(context, lhs, rhs, Some(op), shape)
151 ast::ExprKind::Continue(ref opt_label) => {
152 let id_str = match *opt_label {
153 Some(label) => format!(" {}", label.ident),
154 None => String::new(),
156 Some(format!("continue{}", id_str))
158 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
159 let id_str = match *opt_label {
160 Some(label) => format!(" {}", label.ident),
161 None => String::new(),
164 if let Some(ref expr) = *opt_expr {
165 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
167 Some(format!("break{}", id_str))
170 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
171 rewrite_unary_prefix(context, "yield ", &**expr, shape)
173 Some("yield".to_string())
175 ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
176 closures::rewrite_closure(
186 ast::ExprKind::Try(..)
187 | ast::ExprKind::Field(..)
188 | ast::ExprKind::TupField(..)
189 | ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
190 ast::ExprKind::Mac(ref mac) => {
191 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
193 context.snippet(expr.span).to_owned(),
194 context.config.max_width(),
199 ast::ExprKind::Ret(None) => Some("return".to_owned()),
200 ast::ExprKind::Ret(Some(ref expr)) => {
201 rewrite_unary_prefix(context, "return ", &**expr, shape)
203 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
204 ast::ExprKind::AddrOf(mutability, ref expr) => {
205 rewrite_expr_addrof(context, mutability, expr, shape)
207 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
210 PairParts::new("", " as ", ""),
213 SeparatorPlace::Front,
215 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
218 PairParts::new("", ": ", ""),
221 SeparatorPlace::Back,
223 ast::ExprKind::Index(ref expr, ref index) => {
224 rewrite_index(&**expr, &**index, context, shape)
226 ast::ExprKind::Repeat(ref expr, ref repeats) => {
227 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
235 PairParts::new(lbr, "; ", rbr),
238 SeparatorPlace::Back,
241 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
242 let delim = match limits {
243 ast::RangeLimits::HalfOpen => "..",
244 ast::RangeLimits::Closed => "..=",
247 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
249 ast::ExprKind::Lit(ref lit) => match lit.node {
250 ast::LitKind::FloatUnsuffixed(..) => {
251 context.snippet(lit.span).ends_with('.')
259 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
260 (Some(lhs), Some(rhs)) => {
261 let sp_delim = if context.config.spaces_around_ranges() {
262 format!(" {} ", delim)
263 } else if needs_space_before_range(context, lhs) {
264 format!(" {}", delim)
271 PairParts::new("", &sp_delim, ""),
274 context.config.binop_separator(),
277 (None, Some(rhs)) => {
278 let sp_delim = if context.config.spaces_around_ranges() {
279 format!("{} ", delim)
283 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
285 (Some(lhs), None) => {
286 let sp_delim = if context.config.spaces_around_ranges() {
287 format!(" {}", delim)
291 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
293 (None, None) => Some(delim.to_owned()),
296 // We do not format these expressions yet, but they should still
297 // satisfy our width restrictions.
298 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
299 Some(context.snippet(expr.span).to_owned())
301 ast::ExprKind::Catch(ref block) => {
302 if let rw @ Some(_) =
303 rewrite_single_line_block(context, "do catch ", block, Some(&expr.attrs), shape)
308 let budget = shape.width.checked_sub(9).unwrap_or(0);
316 Shape::legacy(budget, shape.indent)
324 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
325 .and_then(|expr_str| {
326 let attrs = outer_attributes(&expr.attrs);
327 let attrs_str = attrs.rewrite(context, shape)?;
329 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
332 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
336 #[derive(new, Clone, Copy)]
337 pub struct PairParts<'a> {
343 pub fn rewrite_pair<LHS, RHS>(
347 context: &RewriteContext,
349 separator_place: SeparatorPlace,
355 let lhs_overhead = match separator_place {
356 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
357 SeparatorPlace::Front => shape.used_width(),
359 let lhs_shape = Shape {
360 width: context.budget(lhs_overhead),
363 let lhs_result = lhs.rewrite(context, lhs_shape)
364 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
366 // Try to put both lhs and rhs on the same line.
367 let rhs_orig_result = shape
368 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
369 .and_then(|s| s.sub_width(pp.suffix.len()))
370 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
371 if let Some(ref rhs_result) = rhs_orig_result {
372 // If the length of the lhs is equal to or shorter than the tab width or
373 // the rhs looks like block expression, we put the rhs on the same
374 // line with the lhs even if the rhs is multi-lined.
375 let allow_same_line = lhs_result.len() <= context.config.tab_spaces()
379 .map(|first_line| first_line.ends_with('{'))
381 if !rhs_result.contains('\n') || allow_same_line {
382 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
383 + first_line_width(rhs_result) + pp.suffix.len();
384 if one_line_width <= shape.width {
387 lhs_result, pp.infix, rhs_result, pp.suffix
393 // We have to use multiple lines.
394 // Re-evaluate the rhs because we have more space now:
395 let mut rhs_shape = match context.config.indent_style() {
396 IndentStyle::Visual => shape
397 .sub_width(pp.suffix.len() + pp.prefix.len())?
398 .visual_indent(pp.prefix.len()),
399 IndentStyle::Block => {
400 // Try to calculate the initial constraint on the right hand side.
401 let rhs_overhead = shape.rhs_overhead(context.config);
402 Shape::indented(shape.indent.block_indent(context.config), context.config)
403 .sub_width(rhs_overhead)?
406 let infix = match separator_place {
407 SeparatorPlace::Back => pp.infix.trim_right(),
408 SeparatorPlace::Front => pp.infix.trim_left(),
410 if separator_place == SeparatorPlace::Front {
411 rhs_shape = rhs_shape.offset_left(infix.len())?;
413 let rhs_result = rhs.rewrite(context, rhs_shape)?;
414 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
415 let infix_with_sep = match separator_place {
416 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
417 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
421 lhs_result, infix_with_sep, rhs_result, pp.suffix
425 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
428 context: &RewriteContext,
430 trailing_comma: bool,
431 ) -> Option<String> {
432 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
438 let nested_shape = match context.config.indent_style() {
439 IndentStyle::Block => shape
441 .block_indent(context.config.tab_spaces())
442 .with_max_width(context.config)
444 IndentStyle::Visual => shape
445 .visual_indent(bracket_size)
446 .sub_width(bracket_size * 2)?,
449 let items = itemize_list(
450 context.snippet_provider,
454 |item| item.span().lo(),
455 |item| item.span().hi(),
456 |item| item.rewrite(context, nested_shape),
460 ).collect::<Vec<_>>();
462 if items.is_empty() {
463 if context.config.spaces_within_parens_and_brackets() {
464 return Some("[ ]".to_string());
466 return Some("[]".to_string());
470 let tactic = array_tactic(context, shape, nested_shape, exprs, &items, bracket_size);
471 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
473 let fmt = ListFormatting {
476 trailing_separator: if trailing_comma {
477 SeparatorTactic::Always
478 } else if context.inside_macro && !exprs.is_empty() {
479 let ends_with_bracket = context.snippet(span).ends_with(']');
480 let bracket_offset = if ends_with_bracket { 1 } else { 0 };
481 let snippet = context.snippet(mk_sp(span.lo(), span.hi() - BytePos(bracket_offset)));
482 let last_char_index = snippet.rfind(|c: char| !c.is_whitespace())?;
483 if &snippet[last_char_index..last_char_index + 1] == "," {
484 SeparatorTactic::Always
486 SeparatorTactic::Never
488 } else if context.config.indent_style() == IndentStyle::Visual {
489 SeparatorTactic::Never
491 SeparatorTactic::Vertical
493 separator_place: SeparatorPlace::Back,
496 preserve_newline: false,
497 config: context.config,
499 let list_str = write_list(&items, &fmt)?;
501 let result = if context.config.indent_style() == IndentStyle::Visual
502 || tactic == DefinitiveListTactic::Horizontal
504 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
505 format!("[ {} ]", list_str)
507 format!("[{}]", list_str)
512 nested_shape.indent.to_string_with_newline(context.config),
514 shape.block().indent.to_string_with_newline(context.config)
521 fn array_tactic<T: Rewrite + Spanned + ToExpr>(
522 context: &RewriteContext,
528 ) -> DefinitiveListTactic {
529 let has_long_item = items
531 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
533 match context.config.indent_style() {
534 IndentStyle::Block => {
535 let tactic = match shape.width.checked_sub(2 * bracket_size) {
537 let tactic = ListTactic::LimitedHorizontalVertical(
538 context.config.width_heuristics().array_width,
540 definitive_tactic(items, tactic, Separator::Comma, width)
542 None => DefinitiveListTactic::Vertical,
544 if tactic == DefinitiveListTactic::Vertical && !has_long_item
545 && is_every_expr_simple(exprs)
547 DefinitiveListTactic::Mixed
552 IndentStyle::Visual => {
553 if has_long_item || items.iter().any(ListItem::is_multiline) {
556 ListTactic::LimitedHorizontalVertical(
557 context.config.width_heuristics().array_width,
563 DefinitiveListTactic::Mixed
569 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
570 debug!("nop_block_collapse {:?} {}", block_str, budget);
571 block_str.map(|block_str| {
572 if block_str.starts_with('{') && budget >= 2
573 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
582 fn rewrite_empty_block(
583 context: &RewriteContext,
585 attrs: Option<&[ast::Attribute]>,
588 ) -> Option<String> {
589 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
593 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
595 return Some(format!("{}{{}}", prefix));
598 // If a block contains only a single-line comment, then leave it on one line.
599 let user_str = context.snippet(block.span);
600 let user_str = user_str.trim();
601 if user_str.starts_with('{') && user_str.ends_with('}') {
602 let comment_str = user_str[1..user_str.len() - 1].trim();
603 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
604 && comment_str.len() + 4 <= shape.width
606 return Some(format!("{}{{ {} }}", prefix, comment_str));
613 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
614 Some(match block.rules {
615 ast::BlockCheckMode::Unsafe(..) => {
616 let snippet = context.snippet(block.span);
617 let open_pos = snippet.find_uncommented("{")?;
618 // Extract comment between unsafe and block start.
619 let trimmed = &snippet[6..open_pos].trim();
621 if !trimmed.is_empty() {
622 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
623 let budget = shape.width.checked_sub(9)?;
629 Shape::legacy(budget, shape.indent + 7),
637 ast::BlockCheckMode::Default => String::new(),
641 fn rewrite_single_line_block(
642 context: &RewriteContext,
645 attrs: Option<&[ast::Attribute]>,
647 ) -> Option<String> {
648 if is_simple_block(block, attrs, context.codemap) {
649 let expr_shape = shape.offset_left(last_line_width(prefix))?;
650 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
651 let result = format!("{}{{ {} }}", prefix, expr_str);
652 if result.len() <= shape.width && !result.contains('\n') {
659 pub fn rewrite_block_with_visitor(
660 context: &RewriteContext,
663 attrs: Option<&[ast::Attribute]>,
666 ) -> Option<String> {
667 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, prefix, shape) {
671 let mut visitor = FmtVisitor::from_context(context);
672 visitor.block_indent = shape.indent;
673 visitor.is_if_else_block = context.is_if_else_block;
675 ast::BlockCheckMode::Unsafe(..) => {
676 let snippet = context.snippet(block.span);
677 let open_pos = snippet.find_uncommented("{")?;
678 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
680 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
683 let inner_attrs = attrs.map(inner_attributes);
684 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
685 Some(format!("{}{}", prefix, visitor.buffer))
688 impl Rewrite for ast::Block {
689 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
690 rewrite_block(self, None, context, shape)
696 attrs: Option<&[ast::Attribute]>,
697 context: &RewriteContext,
699 ) -> Option<String> {
700 let prefix = block_prefix(context, block, shape)?;
702 // shape.width is used only for the single line case: either the empty block `{}`,
703 // or an unsafe expression `unsafe { e }`.
704 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, &prefix, shape) {
708 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, shape, true);
709 if let Some(ref result_str) = result {
710 if result_str.lines().count() <= 3 {
711 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, block, attrs, shape) {
720 impl Rewrite for ast::Stmt {
721 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
722 skip_out_of_file_lines_range!(context, self.span());
724 let result = match self.node {
725 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
726 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
727 let suffix = if semicolon_for_stmt(context, self) {
733 let shape = shape.sub_width(suffix.len())?;
734 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
736 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
738 result.and_then(|res| recover_comment_removed(res, self.span(), context))
742 // Rewrite condition if the given expression has one.
743 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
745 ast::ExprKind::Match(ref cond, _) => {
747 let cond_shape = match context.config.indent_style() {
748 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
749 IndentStyle::Block => shape.offset_left(8)?,
751 cond.rewrite(context, cond_shape)
753 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
755 String::from("\n") + &shape.indent.block_only().to_string(context.config);
757 .rewrite_cond(context, shape, &alt_block_sep)
758 .and_then(|rw| Some(rw.0))
763 // Abstraction over control flow expressions
765 struct ControlFlow<'a> {
766 cond: Option<&'a ast::Expr>,
767 block: &'a ast::Block,
768 else_block: Option<&'a ast::Expr>,
769 label: Option<ast::Label>,
770 pats: Vec<&'a ast::Pat>,
774 allow_single_line: bool,
775 // True if this is an `if` expression in an `else if` :-( hacky
780 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
782 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
786 else_block.as_ref().map(|e| &**e),
787 expr_type == ExprType::SubExpression,
791 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
792 Some(ControlFlow::new_if(
794 ptr_vec_to_ref_vec(pat),
796 else_block.as_ref().map(|e| &**e),
797 expr_type == ExprType::SubExpression,
802 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
803 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
805 ast::ExprKind::Loop(ref block, label) => {
806 Some(ControlFlow::new_loop(block, label, expr.span))
808 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
815 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
816 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
822 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
830 impl<'a> ControlFlow<'a> {
833 pats: Vec<&'a ast::Pat>,
834 block: &'a ast::Block,
835 else_block: Option<&'a ast::Expr>,
836 allow_single_line: bool,
839 ) -> ControlFlow<'a> {
840 let matcher = choose_matcher(&pats);
856 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
866 allow_single_line: false,
873 pats: Vec<&'a ast::Pat>,
875 block: &'a ast::Block,
876 label: Option<ast::Label>,
878 ) -> ControlFlow<'a> {
879 let matcher = choose_matcher(&pats);
889 allow_single_line: false,
898 block: &'a ast::Block,
899 label: Option<ast::Label>,
901 ) -> ControlFlow<'a> {
911 allow_single_line: false,
917 fn rewrite_single_line(
920 context: &RewriteContext,
922 ) -> Option<String> {
923 assert!(self.allow_single_line);
924 let else_block = self.else_block?;
925 let fixed_cost = self.keyword.len() + " { } else { }".len();
927 if let ast::ExprKind::Block(ref else_node) = else_block.node {
928 if !is_simple_block(self.block, None, context.codemap)
929 || !is_simple_block(else_node, None, context.codemap)
930 || pat_expr_str.contains('\n')
935 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
936 let expr = &self.block.stmts[0];
937 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
939 let new_width = new_width.checked_sub(if_str.len())?;
940 let else_expr = &else_node.stmts[0];
941 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
943 if if_str.contains('\n') || else_str.contains('\n') {
947 let result = format!(
948 "{} {} {{ {} }} else {{ {} }}",
949 self.keyword, pat_expr_str, if_str, else_str
952 if result.len() <= width {
961 impl<'a> ControlFlow<'a> {
964 context: &RewriteContext,
968 ) -> Option<String> {
969 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
971 let cond_shape = shape.offset_left(offset)?;
972 if !self.pats.is_empty() {
973 let matcher = if self.matcher.is_empty() {
974 self.matcher.to_owned()
976 format!("{} ", self.matcher)
978 let pat_shape = cond_shape
979 .offset_left(matcher.len())?
980 .sub_width(self.connector.len())?;
981 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
982 let result = format!("{}{}{}", matcher, pat_string, self.connector);
983 return rewrite_assign_rhs(context, result, expr, cond_shape);
986 let expr_rw = expr.rewrite(context, cond_shape);
987 // The expression may (partially) fit on the current line.
988 // We do not allow splitting between `if` and condition.
989 if self.keyword == "if" || expr_rw.is_some() {
993 // The expression won't fit on the current line, jump to next.
994 let nested_shape = shape
995 .block_indent(context.config.tab_spaces())
996 .with_max_width(context.config);
997 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
998 expr.rewrite(context, nested_shape)
999 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
1004 context: &RewriteContext,
1006 alt_block_sep: &str,
1007 ) -> Option<(String, usize)> {
1008 // Do not take the rhs overhead from the upper expressions into account
1009 // when rewriting pattern.
1010 let new_width = context.budget(shape.used_width());
1011 let fresh_shape = Shape {
1015 let constr_shape = if self.nested_if {
1016 // We are part of an if-elseif-else chain. Our constraints are tightened.
1017 // 7 = "} else " .len()
1018 fresh_shape.offset_left(7)?
1023 let label_string = rewrite_label(self.label);
1024 // 1 = space after keyword.
1025 let offset = self.keyword.len() + label_string.len() + 1;
1027 let pat_expr_string = match self.cond {
1028 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
1029 None => String::new(),
1032 let brace_overhead =
1033 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1039 let one_line_budget = context
1042 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1044 let force_newline_brace = (pat_expr_string.contains('\n')
1045 || pat_expr_string.len() > one_line_budget)
1046 && !last_line_extendable(&pat_expr_string);
1048 // Try to format if-else on single line.
1049 if self.allow_single_line
1053 .single_line_if_else_max_width > 0
1055 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1057 if let Some(cond_str) = trial {
1062 .single_line_if_else_max_width
1064 return Some((cond_str, 0));
1069 let cond_span = if let Some(cond) = self.cond {
1072 mk_sp(self.block.span.lo(), self.block.span.lo())
1075 // `for event in event`
1076 // Do not include label in the span.
1077 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1078 let between_kwd_cond = mk_sp(
1081 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1082 if self.pats.is_empty() {
1084 } else if self.matcher.is_empty() {
1085 self.pats[0].span.lo()
1089 .span_before(self.span, self.matcher.trim())
1093 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1095 let after_cond_comment =
1096 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1098 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1100 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1101 || force_newline_brace
1108 let used_width = if pat_expr_string.contains('\n') {
1109 last_line_width(&pat_expr_string)
1111 // 2 = spaces after keyword and condition.
1112 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1120 between_kwd_cond_comment.as_ref().map_or(
1121 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1129 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1136 impl<'a> Rewrite for ControlFlow<'a> {
1137 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1138 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1140 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1141 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1142 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1143 if used_width == 0 {
1144 return Some(cond_str);
1147 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1148 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1149 // we should avoid the single line case.
1150 let block_width = if self.else_block.is_some() || self.nested_if {
1155 let block_shape = Shape {
1159 let mut block_context = context.clone();
1160 block_context.is_if_else_block = self.else_block.is_some();
1162 rewrite_block_with_visitor(&block_context, "", self.block, None, block_shape, true)?;
1164 let mut result = format!("{}{}", cond_str, block_str);
1166 if let Some(else_block) = self.else_block {
1167 let shape = Shape::indented(shape.indent, context.config);
1168 let mut last_in_chain = false;
1169 let rewrite = match else_block.node {
1170 // If the else expression is another if-else expression, prevent it
1171 // from being formatted on a single line.
1172 // Note how we're passing the original shape, as the
1173 // cost of "else" should not cascade.
1174 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1175 ControlFlow::new_if(
1177 ptr_vec_to_ref_vec(pat),
1179 next_else_block.as_ref().map(|e| &**e),
1182 mk_sp(else_block.span.lo(), self.span.hi()),
1183 ).rewrite(context, shape)
1185 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1186 ControlFlow::new_if(
1190 next_else_block.as_ref().map(|e| &**e),
1193 mk_sp(else_block.span.lo(), self.span.hi()),
1194 ).rewrite(context, shape)
1197 last_in_chain = true;
1198 // When rewriting a block, the width is only used for single line
1199 // blocks, passing 1 lets us avoid that.
1200 let else_shape = Shape {
1201 width: min(1, shape.width),
1204 format_expr(else_block, ExprType::Statement, context, else_shape)
1208 let between_kwd_else_block = mk_sp(
1209 self.block.span.hi(),
1212 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1214 let between_kwd_else_block_comment =
1215 extract_comment(between_kwd_else_block, context, shape);
1217 let after_else = mk_sp(
1220 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1221 else_block.span.lo(),
1223 let after_else_comment = extract_comment(after_else, context, shape);
1225 let between_sep = match context.config.control_brace_style() {
1226 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1229 ControlBraceStyle::AlwaysSameLine => " ",
1231 let after_sep = match context.config.control_brace_style() {
1232 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1236 result.push_str(&format!(
1238 between_kwd_else_block_comment
1240 .map_or(between_sep, |s| &**s),
1241 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1243 result.push_str(&rewrite?);
1250 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1252 Some(label) => Cow::from(format!("{}: ", label.ident)),
1253 None => Cow::from(""),
1257 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1258 match rewrite_missing_comment(span, shape, context) {
1259 Some(ref comment) if !comment.is_empty() => Some(format!(
1260 "{indent}{}{indent}",
1262 indent = shape.indent.to_string_with_newline(context.config)
1268 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1269 let snippet = codemap.span_to_snippet(block.span).unwrap();
1270 contains_comment(&snippet)
1273 // Checks that a block contains no statements, an expression and no comments or
1275 // FIXME: incorrectly returns false when comment is contained completely within
1277 pub fn is_simple_block(
1279 attrs: Option<&[ast::Attribute]>,
1282 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1283 && !block_contains_comment(block, codemap) && attrs.map_or(true, |a| a.is_empty()))
1286 /// Checks whether a block contains at most one statement or expression, and no
1287 /// comments or attributes.
1288 pub fn is_simple_block_stmt(
1290 attrs: Option<&[ast::Attribute]>,
1293 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1294 && attrs.map_or(true, |a| a.is_empty())
1297 /// Checks whether a block contains no statements, expressions, comments, or
1298 /// inner attributes.
1299 pub fn is_empty_block(
1301 attrs: Option<&[ast::Attribute]>,
1304 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1305 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1308 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1310 ast::StmtKind::Expr(..) => true,
1315 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1316 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1323 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
1324 struct ArmWrapper<'a> {
1325 pub arm: &'a ast::Arm,
1326 /// True if the arm is the last one in match expression. Used to decide on whether we should add
1327 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
1329 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
1330 pub beginning_vert: Option<BytePos>,
1333 impl<'a> ArmWrapper<'a> {
1337 beginning_vert: Option<BytePos>,
1338 ) -> ArmWrapper<'a> {
1347 impl<'a> Spanned for ArmWrapper<'a> {
1348 fn span(&self) -> Span {
1349 if let Some(lo) = self.beginning_vert {
1350 mk_sp(lo, self.arm.span().hi())
1357 impl<'a> Rewrite for ArmWrapper<'a> {
1358 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1359 rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
1364 context: &RewriteContext,
1369 attrs: &[ast::Attribute],
1370 ) -> Option<String> {
1371 // Do not take the rhs overhead from the upper expressions into account
1372 // when rewriting match condition.
1373 let cond_shape = Shape {
1374 width: context.budget(shape.used_width()),
1378 let cond_shape = match context.config.indent_style() {
1379 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1380 IndentStyle::Block => cond_shape.offset_left(6)?,
1382 let cond_str = cond.rewrite(context, cond_shape)?;
1383 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1384 let block_sep = match context.config.control_brace_style() {
1385 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1386 _ if last_line_extendable(&cond_str) => " ",
1388 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
1392 let nested_indent_str = shape
1394 .block_indent(context.config)
1395 .to_string(context.config);
1396 // Inner attributes.
1397 let inner_attrs = &inner_attributes(attrs);
1398 let inner_attrs_str = if inner_attrs.is_empty() {
1402 .rewrite(context, shape)
1403 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1406 let open_brace_pos = if inner_attrs.is_empty() {
1407 let hi = if arms.is_empty() {
1414 .span_after(mk_sp(cond.span.hi(), hi), "{")
1416 inner_attrs[inner_attrs.len() - 1].span().hi()
1419 if arms.is_empty() {
1420 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1421 if snippet.trim().is_empty() {
1422 Some(format!("match {} {{}}", cond_str))
1424 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1425 Some(context.snippet(span).to_owned())
1429 "match {}{}{{\n{}{}{}\n{}}}",
1434 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1435 shape.indent.to_string(context.config),
1440 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1441 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1443 } else if config.match_block_trailing_comma() {
1445 } else if let ast::ExprKind::Block(ref block) = body.node {
1446 if let ast::BlockCheckMode::Default = block.rules {
1456 /// Collect a byte position of the beginning `|` for each arm, if available.
1457 fn collect_beginning_verts(
1458 context: &RewriteContext,
1461 ) -> Vec<Option<BytePos>> {
1462 let mut beginning_verts = Vec::with_capacity(arms.len());
1463 let mut lo = context.snippet_provider.span_after(span, "{");
1465 let hi = arm.pats[0].span.lo();
1466 let missing_span = mk_sp(lo, hi);
1467 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
1468 lo = arm.span().hi();
1473 fn rewrite_match_arms(
1474 context: &RewriteContext,
1478 open_brace_pos: BytePos,
1479 ) -> Option<String> {
1480 let arm_shape = shape
1481 .block_indent(context.config.tab_spaces())
1482 .with_max_width(context.config);
1484 let arm_len = arms.len();
1485 let is_last_iter = repeat(false)
1486 .take(arm_len.checked_sub(1).unwrap_or(0))
1487 .chain(repeat(true));
1488 let beginning_verts = collect_beginning_verts(context, arms, span);
1489 let items = itemize_list(
1490 context.snippet_provider,
1493 .zip(beginning_verts.into_iter())
1494 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
1497 |arm| arm.span().lo(),
1498 |arm| arm.span().hi(),
1499 |arm| arm.rewrite(context, arm_shape),
1504 let arms_vec: Vec<_> = items.collect();
1505 let fmt = ListFormatting {
1506 tactic: DefinitiveListTactic::Vertical,
1507 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1509 trailing_separator: SeparatorTactic::Never,
1510 separator_place: SeparatorPlace::Back,
1512 ends_with_newline: true,
1513 preserve_newline: true,
1514 config: context.config,
1517 write_list(&arms_vec, &fmt)
1520 fn rewrite_match_arm(
1521 context: &RewriteContext,
1525 beginning_vert: Option<BytePos>,
1526 ) -> Option<String> {
1527 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1528 if contains_skip(&arm.attrs) {
1529 let (_, body) = flatten_arm_body(context, &arm.body);
1530 // `arm.span()` does not include trailing comma, add it manually.
1531 return Some(format!(
1533 context.snippet(arm.span()),
1534 arm_comma(context.config, body, is_last),
1537 let missing_span = mk_sp(
1538 arm.attrs[arm.attrs.len() - 1].span.hi(),
1539 arm.pats[0].span.lo(),
1541 (missing_span, arm.attrs.rewrite(context, shape)?)
1543 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1545 let pats_str = rewrite_match_pattern(
1547 &ptr_vec_to_ref_vec(&arm.pats),
1549 beginning_vert.is_some(),
1551 ).and_then(|pats_str| {
1552 combine_strs_with_missing_comments(
1566 arm.guard.is_some(),
1571 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
1575 /// - `&[single-line, ntp]`
1578 /// - `[small, ntp]`
1579 /// - unary tuple constructor `([small, ntp])`
1581 fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
1582 // We also require that the pattern is reasonably 'small' with its literal width.
1583 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
1586 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
1588 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
1589 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
1590 ast::PatKind::Struct(..)
1591 | ast::PatKind::Mac(..)
1592 | ast::PatKind::Slice(..)
1593 | ast::PatKind::Path(..)
1594 | ast::PatKind::Range(..) => false,
1595 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
1596 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
1597 path.segments.len() <= 1 && subpats.len() <= 1
1599 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
1600 is_short_pattern_inner(&*p)
1605 fn rewrite_match_pattern(
1606 context: &RewriteContext,
1608 guard: &Option<ptr::P<ast::Expr>>,
1609 has_beginning_vert: bool,
1611 ) -> Option<String> {
1615 let pat_shape = shape
1617 .offset_left(if has_beginning_vert { 2 } else { 0 })?;
1618 let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
1619 let beginning_vert = if has_beginning_vert { "| " } else { "" };
1622 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1624 Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
1628 // @extend: true if the arm body can be put next to `=>`
1629 // @body: flattened body, if the body is block with a single expression
1630 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1632 ast::ExprKind::Block(ref block)
1633 if !is_unsafe_block(block)
1634 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
1636 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1638 !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
1646 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
1652 fn rewrite_match_body(
1653 context: &RewriteContext,
1654 body: &ptr::P<ast::Expr>,
1659 ) -> Option<String> {
1660 let (extend, body) = flatten_arm_body(context, body);
1661 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1664 is_empty_block(block, Some(&body.attrs), context.codemap),
1670 let comma = arm_comma(context.config, body, is_last);
1671 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1673 let combine_orig_body = |body_str: &str| {
1674 let block_sep = match context.config.control_brace_style() {
1675 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1679 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1682 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1683 let next_line_indent = if !is_block || is_empty_block {
1684 shape.indent.block_indent(context.config)
1688 let combine_next_line_body = |body_str: &str| {
1690 return Some(format!(
1693 next_line_indent.to_string_with_newline(context.config),
1698 let indent_str = shape.indent.to_string_with_newline(context.config);
1699 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
1700 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
1701 let comma = if context.config.match_block_trailing_comma() {
1706 ("{", format!("{}}}{}", indent_str, comma))
1708 ("", String::from(","))
1711 let block_sep = match context.config.control_brace_style() {
1712 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
1713 _ if body_prefix.is_empty() => "".to_owned(),
1714 _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
1715 _ => format!(" {}", body_prefix),
1716 } + &nested_indent_str;
1720 pats_str, block_sep, body_str, body_suffix
1724 // Let's try and get the arm body on the same line as the condition.
1726 let orig_body_shape = shape
1727 .offset_left(extra_offset(pats_str, shape) + 4)
1728 .and_then(|shape| shape.sub_width(comma.len()));
1729 let orig_body = if let Some(body_shape) = orig_body_shape {
1730 let rewrite = nop_block_collapse(
1731 format_expr(body, ExprType::Statement, context, body_shape),
1737 if !forbid_same_line
1739 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1741 return combine_orig_body(body_str);
1748 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1750 // Try putting body on the next line and see if it looks better.
1751 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1752 let next_line_body = nop_block_collapse(
1753 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1754 next_line_body_shape.width,
1756 match (orig_body, next_line_body) {
1757 (Some(ref orig_str), Some(ref next_line_str))
1759 || prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
1761 combine_next_line_body(next_line_str)
1763 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1764 combine_orig_body(orig_str)
1766 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1767 combine_next_line_body(next_line_str)
1769 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1770 (None, None) => None,
1771 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1775 // The `if ...` guard on a match arm.
1777 context: &RewriteContext,
1778 guard: &Option<ptr::P<ast::Expr>>,
1780 // The amount of space used up on this line for the pattern in
1781 // the arm (excludes offset).
1782 pattern_width: usize,
1783 ) -> Option<String> {
1784 if let Some(ref guard) = *guard {
1785 // First try to fit the guard string on the same line as the pattern.
1786 // 4 = ` if `, 5 = ` => {`
1787 let cond_shape = shape
1788 .offset_left(pattern_width + 4)
1789 .and_then(|s| s.sub_width(5));
1790 if let Some(cond_shape) = cond_shape {
1791 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1792 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1793 return Some(format!(" if {}", cond_str));
1798 // Not enough space to put the guard after the pattern, try a newline.
1799 // 3 = `if `, 5 = ` => {`
1800 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1802 .and_then(|s| s.sub_width(5));
1803 if let Some(cond_shape) = cond_shape {
1804 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1805 return Some(format!(
1807 cond_shape.indent.to_string_with_newline(context.config),
1819 fn rewrite_multiple_patterns(
1820 context: &RewriteContext,
1823 ) -> Option<String> {
1824 let pat_strs = pats.iter()
1825 .map(|p| p.rewrite(context, shape))
1826 .collect::<Option<Vec<_>>>()?;
1828 let use_mixed_layout = pats.iter()
1829 .zip(pat_strs.iter())
1830 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1831 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1832 let tactic = if use_mixed_layout {
1833 DefinitiveListTactic::Mixed
1837 ListTactic::HorizontalVertical,
1838 Separator::VerticalBar,
1842 let fmt = ListFormatting {
1845 trailing_separator: SeparatorTactic::Never,
1846 separator_place: context.config.binop_separator(),
1848 ends_with_newline: false,
1849 preserve_newline: false,
1850 config: context.config,
1852 write_list(&items, &fmt)
1855 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
1857 // We do not allow `if` to stay on the same line, since we could easily mistake
1858 // `pat => if cond { ... }` and `pat if cond => { ... }`.
1859 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
1860 ast::ExprKind::ForLoop(..)
1861 | ast::ExprKind::Loop(..)
1862 | ast::ExprKind::While(..)
1863 | ast::ExprKind::WhileLet(..)
1864 | ast::ExprKind::Match(..)
1865 | ast::ExprKind::Block(..)
1866 | ast::ExprKind::Closure(..)
1867 | ast::ExprKind::Array(..)
1868 | ast::ExprKind::Call(..)
1869 | ast::ExprKind::MethodCall(..)
1870 | ast::ExprKind::Mac(..)
1871 | ast::ExprKind::Struct(..)
1872 | ast::ExprKind::Tup(..) => true,
1873 ast::ExprKind::AddrOf(_, ref expr)
1874 | ast::ExprKind::Box(ref expr)
1875 | ast::ExprKind::Try(ref expr)
1876 | ast::ExprKind::Unary(_, ref expr)
1877 | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
1882 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1884 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1886 context.snippet(l.span).to_owned(),
1887 context.config.max_width(),
1893 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1894 let string_lit = context.snippet(span);
1896 if !context.config.format_strings() {
1901 .all(|line| line.ends_with('\\'))
1903 let new_indent = shape.visual_indent(1).indent;
1904 let indented_string_lit = String::from(
1910 new_indent.to_string(context.config),
1914 .collect::<Vec<_>>()
1918 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1920 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1924 // Remove the quote characters.
1925 let str_lit = &string_lit[1..string_lit.len() - 1];
1929 &StringFormat::new(shape.visual_indent(0), context.config),
1934 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1935 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1936 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1938 .find(|&&(s, _)| s == callee_str)
1940 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1942 Some((all_simple, num_args_before))
1948 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1951 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1952 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1953 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1954 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1955 // format! like macros
1956 // From the Rust Standard Library.
1960 ("format_args!", 0),
1964 ("unreachable!", 0),
1965 // From the `log` crate.
1970 // write! like macros
1972 ("debug_assert!", 1),
1975 // assert_eq! like macros
1978 ("debug_assert_eq!", 2),
1979 ("debug_assert_ne!", 2),
1982 pub fn rewrite_call(
1983 context: &RewriteContext,
1985 args: &[ptr::P<ast::Expr>],
1988 ) -> Option<String> {
1989 overflow::rewrite_with_parens(
1992 &ptr_vec_to_ref_vec(args),
1995 context.config.width_heuristics().fn_call_width,
1996 if context.inside_macro {
1997 if span_ends_with_comma(context, span) {
1998 Some(SeparatorTactic::Always)
2000 Some(SeparatorTactic::Never)
2008 fn is_simple_expr(expr: &ast::Expr) -> bool {
2010 ast::ExprKind::Lit(..) => true,
2011 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
2012 ast::ExprKind::AddrOf(_, ref expr)
2013 | ast::ExprKind::Box(ref expr)
2014 | ast::ExprKind::Cast(ref expr, _)
2015 | ast::ExprKind::Field(ref expr, _)
2016 | ast::ExprKind::Try(ref expr)
2017 | ast::ExprKind::TupField(ref expr, _)
2018 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
2019 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
2020 is_simple_expr(lhs) && is_simple_expr(rhs)
2026 fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
2029 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
2032 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2034 ast::ExprKind::Match(..) => {
2035 (context.use_block_indent() && args_len == 1)
2036 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
2038 ast::ExprKind::If(..)
2039 | ast::ExprKind::IfLet(..)
2040 | ast::ExprKind::ForLoop(..)
2041 | ast::ExprKind::Loop(..)
2042 | ast::ExprKind::While(..)
2043 | ast::ExprKind::WhileLet(..) => {
2044 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2046 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2047 context.use_block_indent()
2048 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
2050 ast::ExprKind::Array(..)
2051 | ast::ExprKind::Call(..)
2052 | ast::ExprKind::Mac(..)
2053 | ast::ExprKind::MethodCall(..)
2054 | ast::ExprKind::Struct(..)
2055 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2056 ast::ExprKind::AddrOf(_, ref expr)
2057 | ast::ExprKind::Box(ref expr)
2058 | ast::ExprKind::Try(ref expr)
2059 | ast::ExprKind::Unary(_, ref expr)
2060 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2065 pub fn is_nested_call(expr: &ast::Expr) -> bool {
2067 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
2068 ast::ExprKind::AddrOf(_, ref expr)
2069 | ast::ExprKind::Box(ref expr)
2070 | ast::ExprKind::Try(ref expr)
2071 | ast::ExprKind::Unary(_, ref expr)
2072 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
2077 /// Return true if a function call or a method call represented by the given span ends with a
2078 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2079 /// comma from macro can potentially break the code.
2080 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2081 let mut result: bool = Default::default();
2082 let mut prev_char: char = Default::default();
2084 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
2086 _ if kind.is_comment() || c.is_whitespace() => continue,
2087 ')' | '}' => result = result && prev_char != c,
2088 ',' => result = true,
2089 _ => result = false,
2098 context: &RewriteContext,
2099 mut subexpr: &ast::Expr,
2102 ) -> Option<String> {
2103 debug!("rewrite_paren, shape: {:?}", shape);
2105 // Extract comments within parens.
2106 let mut pre_comment;
2107 let mut post_comment;
2110 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
2111 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
2112 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
2113 post_comment = rewrite_missing_comment(post_span, shape, context)?;
2115 // Remove nested parens if there are no comments.
2116 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
2117 if pre_comment.is_empty() && post_comment.is_empty() {
2118 span = subexpr.span;
2119 subexpr = subsubexpr;
2127 let total_paren_overhead = paren_overhead(context);
2128 let paren_overhead = total_paren_overhead / 2;
2129 let sub_shape = shape
2130 .offset_left(paren_overhead)
2131 .and_then(|s| s.sub_width(paren_overhead))?;
2133 let paren_wrapper = |s: &str| {
2134 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2135 format!("( {}{}{} )", pre_comment, s, post_comment)
2137 format!("({}{}{})", pre_comment, s, post_comment)
2141 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2142 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2144 if subexpr_str.contains('\n')
2145 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2147 Some(paren_wrapper(&subexpr_str))
2156 context: &RewriteContext,
2158 ) -> Option<String> {
2159 let expr_str = expr.rewrite(context, shape)?;
2161 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2167 let offset = last_line_width(&expr_str) + lbr.len();
2168 let rhs_overhead = shape.rhs_overhead(context.config);
2169 let index_shape = if expr_str.contains('\n') {
2170 Shape::legacy(context.config.max_width(), shape.indent)
2171 .offset_left(offset)
2172 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2174 shape.visual_indent(offset).sub_width(offset + rbr.len())
2176 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2178 // Return if index fits in a single line.
2179 match orig_index_rw {
2180 Some(ref index_str) if !index_str.contains('\n') => {
2181 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2186 // Try putting index on the next line and see if it fits in a single line.
2187 let indent = shape.indent.block_indent(context.config);
2188 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2189 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2190 let new_index_rw = index.rewrite(context, index_shape);
2191 match (orig_index_rw, new_index_rw) {
2192 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2195 indent.to_string_with_newline(context.config),
2200 (None, Some(ref new_index_str)) => Some(format!(
2203 indent.to_string_with_newline(context.config),
2208 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2213 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2218 fields.iter().all(|field| !field.is_shorthand)
2221 fn rewrite_struct_lit<'a>(
2222 context: &RewriteContext,
2224 fields: &'a [ast::Field],
2225 base: Option<&'a ast::Expr>,
2228 ) -> Option<String> {
2229 debug!("rewrite_struct_lit: shape {:?}", shape);
2231 enum StructLitField<'a> {
2232 Regular(&'a ast::Field),
2233 Base(&'a ast::Expr),
2237 let path_shape = shape.sub_width(2)?;
2238 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2240 if fields.is_empty() && base.is_none() {
2241 return Some(format!("{} {{}}", path_str));
2244 // Foo { a: Foo } - indent is +3, width is -5.
2245 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2247 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2248 let body_lo = context.snippet_provider.span_after(span, "{");
2249 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2250 && context.config.struct_field_align_threshold() > 0
2252 rewrite_with_alignment(
2256 mk_sp(body_lo, span.hi()),
2260 let field_iter = fields
2262 .map(StructLitField::Regular)
2263 .chain(base.into_iter().map(StructLitField::Base));
2265 let span_lo = |item: &StructLitField| match *item {
2266 StructLitField::Regular(field) => field.span().lo(),
2267 StructLitField::Base(expr) => {
2268 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2269 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2270 let pos = snippet.find_uncommented("..").unwrap();
2271 last_field_hi + BytePos(pos as u32)
2274 let span_hi = |item: &StructLitField| match *item {
2275 StructLitField::Regular(field) => field.span().hi(),
2276 StructLitField::Base(expr) => expr.span.hi(),
2278 let rewrite = |item: &StructLitField| match *item {
2279 StructLitField::Regular(field) => {
2280 // The 1 taken from the v_budget is for the comma.
2281 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2283 StructLitField::Base(expr) => {
2285 expr.rewrite(context, v_shape.offset_left(2)?)
2286 .map(|s| format!("..{}", s))
2290 let items = itemize_list(
2291 context.snippet_provider,
2302 let item_vec = items.collect::<Vec<_>>();
2304 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2305 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2307 let ends_with_comma = span_ends_with_comma(context, span);
2308 let force_no_trailing_comma = if context.inside_macro && !ends_with_comma {
2314 let fmt = struct_lit_formatting(
2318 force_no_trailing_comma || base.is_some(),
2321 write_list(&item_vec, &fmt)?
2324 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2325 Some(format!("{} {{{}}}", path_str, fields_str))
2327 // FIXME if context.config.indent_style() == Visual, but we run out
2328 // of space, we should fall back to BlockIndent.
2331 pub fn wrap_struct_field(
2332 context: &RewriteContext,
2335 nested_shape: Shape,
2336 one_line_width: usize,
2338 if context.config.indent_style() == IndentStyle::Block
2339 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
2340 || fields_str.len() > one_line_width)
2344 nested_shape.indent.to_string_with_newline(context.config),
2346 shape.indent.to_string_with_newline(context.config)
2349 // One liner or visual indent.
2350 format!(" {} ", fields_str)
2354 pub fn struct_lit_field_separator(config: &Config) -> &str {
2355 colon_spaces(config.space_before_colon(), config.space_after_colon())
2358 pub fn rewrite_field(
2359 context: &RewriteContext,
2362 prefix_max_width: usize,
2363 ) -> Option<String> {
2364 if contains_skip(&field.attrs) {
2365 return Some(context.snippet(field.span()).to_owned());
2367 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2368 if !attrs_str.is_empty() {
2369 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
2371 let name = field.ident.node.to_string();
2372 if field.is_shorthand {
2373 Some(attrs_str + &name)
2375 let mut separator = String::from(struct_lit_field_separator(context.config));
2376 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2377 separator.push(' ');
2379 let overhead = name.len() + separator.len();
2380 let expr_shape = shape.offset_left(overhead)?;
2381 let expr = field.expr.rewrite(context, expr_shape);
2384 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
2385 Some(attrs_str + &name)
2387 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2389 let expr_offset = shape.indent.block_indent(context.config);
2392 .rewrite(context, Shape::indented(expr_offset, context.config));
2398 expr_offset.to_string(context.config),
2407 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2408 context: &RewriteContext,
2414 T: Rewrite + Spanned + ToExpr + 'a,
2416 let mut items = items.iter();
2417 // In case of length 1, need a trailing comma
2418 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2419 if items.len() == 1 {
2421 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2425 .rewrite(context, nested_shape)
2427 if context.config.spaces_within_parens_and_brackets() {
2428 format!("( {}, )", s)
2435 let list_lo = context.snippet_provider.span_after(span, "(");
2436 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2437 let items = itemize_list(
2438 context.snippet_provider,
2442 |item| item.span().lo(),
2443 |item| item.span().hi(),
2444 |item| item.rewrite(context, nested_shape),
2446 span.hi() - BytePos(1),
2449 let item_vec: Vec<_> = items.collect();
2450 let tactic = definitive_tactic(
2452 ListTactic::HorizontalVertical,
2456 let fmt = ListFormatting {
2459 trailing_separator: SeparatorTactic::Never,
2460 separator_place: SeparatorPlace::Back,
2462 ends_with_newline: false,
2463 preserve_newline: false,
2464 config: context.config,
2466 let list_str = write_list(&item_vec, &fmt)?;
2468 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2469 Some(format!("( {} )", list_str))
2471 Some(format!("({})", list_str))
2475 pub fn rewrite_tuple<'a, T>(
2476 context: &RewriteContext,
2482 T: Rewrite + Spanned + ToExpr + 'a,
2484 debug!("rewrite_tuple {:?}", shape);
2485 if context.use_block_indent() {
2486 // We use the same rule as function calls for rewriting tuples.
2487 let force_tactic = if context.inside_macro {
2488 if span_ends_with_comma(context, span) {
2489 Some(SeparatorTactic::Always)
2491 Some(SeparatorTactic::Never)
2494 if items.len() == 1 {
2495 Some(SeparatorTactic::Always)
2500 overflow::rewrite_with_parens(
2506 context.config.width_heuristics().fn_call_width,
2510 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2514 pub fn rewrite_unary_prefix<R: Rewrite>(
2515 context: &RewriteContext,
2519 ) -> Option<String> {
2521 .rewrite(context, shape.offset_left(prefix.len())?)
2522 .map(|r| format!("{}{}", prefix, r))
2525 // FIXME: this is probably not correct for multi-line Rewrites. we should
2526 // subtract suffix.len() from the last line budget, not the first!
2527 pub fn rewrite_unary_suffix<R: Rewrite>(
2528 context: &RewriteContext,
2532 ) -> Option<String> {
2534 .rewrite(context, shape.sub_width(suffix.len())?)
2541 fn rewrite_unary_op(
2542 context: &RewriteContext,
2546 ) -> Option<String> {
2547 // For some reason, an UnOp is not spanned like BinOp!
2548 let operator_str = match *op {
2549 ast::UnOp::Deref => "*",
2550 ast::UnOp::Not => "!",
2551 ast::UnOp::Neg => "-",
2553 rewrite_unary_prefix(context, operator_str, expr, shape)
2556 fn rewrite_assignment(
2557 context: &RewriteContext,
2560 op: Option<&ast::BinOp>,
2562 ) -> Option<String> {
2563 let operator_str = match op {
2564 Some(op) => context.snippet(op.span),
2568 // 1 = space between lhs and operator.
2569 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2570 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2572 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2575 /// Controls where to put the rhs.
2576 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2577 pub enum RhsTactics {
2580 /// Put the rhs on the next line if it uses multiple line.
2584 // The left hand side must contain everything up to, and including, the
2585 // assignment operator.
2586 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2587 context: &RewriteContext,
2591 ) -> Option<String> {
2592 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
2595 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2596 context: &RewriteContext,
2600 rhs_tactics: RhsTactics,
2601 ) -> Option<String> {
2602 let lhs = lhs.into();
2603 let last_line_width = last_line_width(&lhs)
2604 .checked_sub(if lhs.contains('\n') {
2605 shape.indent.width()
2610 // 1 = space between operator and rhs.
2611 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2613 offset: shape.offset + last_line_width + 1,
2616 let rhs = choose_rhs(
2620 ex.rewrite(context, orig_shape),
2626 fn choose_rhs<R: Rewrite>(
2627 context: &RewriteContext,
2630 orig_rhs: Option<String>,
2631 rhs_tactics: RhsTactics,
2632 ) -> Option<String> {
2634 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2635 Some(format!(" {}", new_str))
2638 // Expression did not fit on the same line as the identifier.
2639 // Try splitting the line and see if that works better.
2641 Shape::indented(shape.indent.block_indent(context.config), context.config)
2642 .sub_width(shape.rhs_overhead(context.config))?;
2643 let new_rhs = expr.rewrite(context, new_shape);
2644 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2646 match (orig_rhs, new_rhs) {
2647 (Some(ref orig_rhs), Some(ref new_rhs))
2648 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2651 Some(format!(" {}", orig_rhs))
2653 (Some(ref orig_rhs), Some(ref new_rhs))
2654 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2656 Some(format!("{}{}", new_indent_str, new_rhs))
2658 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2659 (None, None) => None,
2660 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2666 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2667 rhs_tactics == RhsTactics::ForceNextLine || !next_line_rhs.contains('\n')
2668 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2671 fn rewrite_expr_addrof(
2672 context: &RewriteContext,
2673 mutability: ast::Mutability,
2676 ) -> Option<String> {
2677 let operator_str = match mutability {
2678 ast::Mutability::Immutable => "&",
2679 ast::Mutability::Mutable => "&mut ",
2681 rewrite_unary_prefix(context, operator_str, expr, shape)
2685 fn to_expr(&self) -> Option<&ast::Expr>;
2686 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2689 impl ToExpr for ast::Expr {
2690 fn to_expr(&self) -> Option<&ast::Expr> {
2694 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2695 can_be_overflowed_expr(context, self, len)
2699 impl ToExpr for ast::Ty {
2700 fn to_expr(&self) -> Option<&ast::Expr> {
2704 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2705 can_be_overflowed_type(context, self, len)
2709 impl<'a> ToExpr for TuplePatField<'a> {
2710 fn to_expr(&self) -> Option<&ast::Expr> {
2714 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2715 can_be_overflowed_pat(context, self, len)
2719 impl<'a> ToExpr for ast::StructField {
2720 fn to_expr(&self) -> Option<&ast::Expr> {
2724 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2729 impl<'a> ToExpr for MacroArg {
2730 fn to_expr(&self) -> Option<&ast::Expr> {
2732 MacroArg::Expr(ref expr) => Some(expr),
2737 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2739 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2740 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2741 MacroArg::Pat(..) => false,
2742 MacroArg::Item(..) => len == 1,
2747 impl ToExpr for ast::GenericParam {
2748 fn to_expr(&self) -> Option<&ast::Expr> {
2752 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {