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 rhs looks like block expression, we allow it to stay on the same line
373 // with the lhs even if it is multi-lined.
374 let allow_same_line = rhs_result
377 .map(|first_line| first_line.ends_with('{'))
379 if !rhs_result.contains('\n') || allow_same_line {
380 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
381 + first_line_width(rhs_result) + pp.suffix.len();
382 if one_line_width <= shape.width {
385 lhs_result, pp.infix, rhs_result, pp.suffix
391 // We have to use multiple lines.
392 // Re-evaluate the rhs because we have more space now:
393 let mut rhs_shape = match context.config.indent_style() {
394 IndentStyle::Visual => shape
395 .sub_width(pp.suffix.len() + pp.prefix.len())?
396 .visual_indent(pp.prefix.len()),
397 IndentStyle::Block => {
398 // Try to calculate the initial constraint on the right hand side.
399 let rhs_overhead = shape.rhs_overhead(context.config);
400 Shape::indented(shape.indent.block_indent(context.config), context.config)
401 .sub_width(rhs_overhead)?
404 let infix = match separator_place {
405 SeparatorPlace::Back => pp.infix.trim_right(),
406 SeparatorPlace::Front => pp.infix.trim_left(),
408 if separator_place == SeparatorPlace::Front {
409 rhs_shape = rhs_shape.offset_left(infix.len())?;
411 let rhs_result = rhs.rewrite(context, rhs_shape)?;
412 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
413 let infix_with_sep = match separator_place {
414 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
415 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
419 lhs_result, infix_with_sep, rhs_result, pp.suffix
423 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
426 context: &RewriteContext,
428 trailing_comma: bool,
429 ) -> Option<String> {
430 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
436 let nested_shape = match context.config.indent_style() {
437 IndentStyle::Block => shape
439 .block_indent(context.config.tab_spaces())
440 .with_max_width(context.config)
442 IndentStyle::Visual => shape
443 .visual_indent(bracket_size)
444 .sub_width(bracket_size * 2)?,
447 let items = itemize_list(
448 context.snippet_provider,
452 |item| item.span().lo(),
453 |item| item.span().hi(),
454 |item| item.rewrite(context, nested_shape),
458 ).collect::<Vec<_>>();
460 if items.is_empty() {
461 if context.config.spaces_within_parens_and_brackets() {
462 return Some("[ ]".to_string());
464 return Some("[]".to_string());
468 let tactic = array_tactic(context, shape, nested_shape, exprs, &items, bracket_size);
469 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
471 let fmt = ListFormatting {
474 trailing_separator: if trailing_comma {
475 SeparatorTactic::Always
476 } else if context.inside_macro && !exprs.is_empty() {
477 let ends_with_bracket = context.snippet(span).ends_with(']');
478 let bracket_offset = if ends_with_bracket { 1 } else { 0 };
479 let snippet = context.snippet(mk_sp(span.lo(), span.hi() - BytePos(bracket_offset)));
480 let last_char_index = snippet.rfind(|c: char| !c.is_whitespace())?;
481 if &snippet[last_char_index..last_char_index + 1] == "," {
482 SeparatorTactic::Always
484 SeparatorTactic::Never
486 } else if context.config.indent_style() == IndentStyle::Visual {
487 SeparatorTactic::Never
489 SeparatorTactic::Vertical
491 separator_place: SeparatorPlace::Back,
494 preserve_newline: false,
495 config: context.config,
497 let list_str = write_list(&items, &fmt)?;
499 let result = if context.config.indent_style() == IndentStyle::Visual
500 || tactic == DefinitiveListTactic::Horizontal
502 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
503 format!("[ {} ]", list_str)
505 format!("[{}]", list_str)
510 nested_shape.indent.to_string_with_newline(context.config),
512 shape.block().indent.to_string_with_newline(context.config)
519 fn array_tactic<T: Rewrite + Spanned + ToExpr>(
520 context: &RewriteContext,
526 ) -> DefinitiveListTactic {
527 let has_long_item = items
529 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
531 match context.config.indent_style() {
532 IndentStyle::Block => {
533 let tactic = match shape.width.checked_sub(2 * bracket_size) {
535 let tactic = ListTactic::LimitedHorizontalVertical(
536 context.config.width_heuristics().array_width,
538 definitive_tactic(items, tactic, Separator::Comma, width)
540 None => DefinitiveListTactic::Vertical,
542 if tactic == DefinitiveListTactic::Vertical && !has_long_item
543 && is_every_expr_simple(exprs)
545 DefinitiveListTactic::Mixed
550 IndentStyle::Visual => {
551 if has_long_item || items.iter().any(ListItem::is_multiline) {
554 ListTactic::LimitedHorizontalVertical(
555 context.config.width_heuristics().array_width,
561 DefinitiveListTactic::Mixed
567 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
568 debug!("nop_block_collapse {:?} {}", block_str, budget);
569 block_str.map(|block_str| {
570 if block_str.starts_with('{') && budget >= 2
571 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
580 fn rewrite_empty_block(
581 context: &RewriteContext,
583 attrs: Option<&[ast::Attribute]>,
586 ) -> Option<String> {
587 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
591 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
593 return Some(format!("{}{{}}", prefix));
596 // If a block contains only a single-line comment, then leave it on one line.
597 let user_str = context.snippet(block.span);
598 let user_str = user_str.trim();
599 if user_str.starts_with('{') && user_str.ends_with('}') {
600 let comment_str = user_str[1..user_str.len() - 1].trim();
601 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
602 && comment_str.len() + 4 <= shape.width
604 return Some(format!("{}{{ {} }}", prefix, comment_str));
611 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
612 Some(match block.rules {
613 ast::BlockCheckMode::Unsafe(..) => {
614 let snippet = context.snippet(block.span);
615 let open_pos = snippet.find_uncommented("{")?;
616 // Extract comment between unsafe and block start.
617 let trimmed = &snippet[6..open_pos].trim();
619 if !trimmed.is_empty() {
620 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
621 let budget = shape.width.checked_sub(9)?;
627 Shape::legacy(budget, shape.indent + 7),
635 ast::BlockCheckMode::Default => String::new(),
639 fn rewrite_single_line_block(
640 context: &RewriteContext,
643 attrs: Option<&[ast::Attribute]>,
645 ) -> Option<String> {
646 if is_simple_block(block, attrs, context.codemap) {
647 let expr_shape = shape.offset_left(last_line_width(prefix))?;
648 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
649 let result = format!("{}{{ {} }}", prefix, expr_str);
650 if result.len() <= shape.width && !result.contains('\n') {
657 pub fn rewrite_block_with_visitor(
658 context: &RewriteContext,
661 attrs: Option<&[ast::Attribute]>,
664 ) -> Option<String> {
665 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, prefix, shape) {
669 let mut visitor = FmtVisitor::from_context(context);
670 visitor.block_indent = shape.indent;
671 visitor.is_if_else_block = context.is_if_else_block;
673 ast::BlockCheckMode::Unsafe(..) => {
674 let snippet = context.snippet(block.span);
675 let open_pos = snippet.find_uncommented("{")?;
676 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
678 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
681 let inner_attrs = attrs.map(inner_attributes);
682 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
683 Some(format!("{}{}", prefix, visitor.buffer))
686 impl Rewrite for ast::Block {
687 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
688 rewrite_block(self, None, context, shape)
694 attrs: Option<&[ast::Attribute]>,
695 context: &RewriteContext,
697 ) -> Option<String> {
698 let prefix = block_prefix(context, block, shape)?;
700 // shape.width is used only for the single line case: either the empty block `{}`,
701 // or an unsafe expression `unsafe { e }`.
702 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, &prefix, shape) {
706 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, shape, true);
707 if let Some(ref result_str) = result {
708 if result_str.lines().count() <= 3 {
709 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, block, attrs, shape) {
718 impl Rewrite for ast::Stmt {
719 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
720 skip_out_of_file_lines_range!(context, self.span());
722 let result = match self.node {
723 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
724 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
725 let suffix = if semicolon_for_stmt(context, self) {
731 let shape = shape.sub_width(suffix.len())?;
732 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
734 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
736 result.and_then(|res| recover_comment_removed(res, self.span(), context))
740 // Rewrite condition if the given expression has one.
741 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
743 ast::ExprKind::Match(ref cond, _) => {
745 let cond_shape = match context.config.indent_style() {
746 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
747 IndentStyle::Block => shape.offset_left(8)?,
749 cond.rewrite(context, cond_shape)
751 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
753 String::from("\n") + &shape.indent.block_only().to_string(context.config);
755 .rewrite_cond(context, shape, &alt_block_sep)
756 .and_then(|rw| Some(rw.0))
761 // Abstraction over control flow expressions
763 struct ControlFlow<'a> {
764 cond: Option<&'a ast::Expr>,
765 block: &'a ast::Block,
766 else_block: Option<&'a ast::Expr>,
767 label: Option<ast::Label>,
768 pats: Vec<&'a ast::Pat>,
772 allow_single_line: bool,
773 // True if this is an `if` expression in an `else if` :-( hacky
778 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
780 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
784 else_block.as_ref().map(|e| &**e),
785 expr_type == ExprType::SubExpression,
789 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
790 Some(ControlFlow::new_if(
792 ptr_vec_to_ref_vec(pat),
794 else_block.as_ref().map(|e| &**e),
795 expr_type == ExprType::SubExpression,
800 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
801 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
803 ast::ExprKind::Loop(ref block, label) => {
804 Some(ControlFlow::new_loop(block, label, expr.span))
806 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
813 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
814 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
820 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
828 impl<'a> ControlFlow<'a> {
831 pats: Vec<&'a ast::Pat>,
832 block: &'a ast::Block,
833 else_block: Option<&'a ast::Expr>,
834 allow_single_line: bool,
837 ) -> ControlFlow<'a> {
838 let matcher = choose_matcher(&pats);
854 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
864 allow_single_line: false,
871 pats: Vec<&'a ast::Pat>,
873 block: &'a ast::Block,
874 label: Option<ast::Label>,
876 ) -> ControlFlow<'a> {
877 let matcher = choose_matcher(&pats);
887 allow_single_line: false,
896 block: &'a ast::Block,
897 label: Option<ast::Label>,
899 ) -> ControlFlow<'a> {
909 allow_single_line: false,
915 fn rewrite_single_line(
918 context: &RewriteContext,
920 ) -> Option<String> {
921 assert!(self.allow_single_line);
922 let else_block = self.else_block?;
923 let fixed_cost = self.keyword.len() + " { } else { }".len();
925 if let ast::ExprKind::Block(ref else_node) = else_block.node {
926 if !is_simple_block(self.block, None, context.codemap)
927 || !is_simple_block(else_node, None, context.codemap)
928 || pat_expr_str.contains('\n')
933 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
934 let expr = &self.block.stmts[0];
935 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
937 let new_width = new_width.checked_sub(if_str.len())?;
938 let else_expr = &else_node.stmts[0];
939 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
941 if if_str.contains('\n') || else_str.contains('\n') {
945 let result = format!(
946 "{} {} {{ {} }} else {{ {} }}",
947 self.keyword, pat_expr_str, if_str, else_str
950 if result.len() <= width {
959 impl<'a> ControlFlow<'a> {
962 context: &RewriteContext,
966 ) -> Option<String> {
967 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
969 let cond_shape = shape.offset_left(offset)?;
970 if !self.pats.is_empty() {
971 let matcher = if self.matcher.is_empty() {
972 self.matcher.to_owned()
974 format!("{} ", self.matcher)
976 let pat_shape = cond_shape
977 .offset_left(matcher.len())?
978 .sub_width(self.connector.len())?;
979 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
980 let result = format!("{}{}{}", matcher, pat_string, self.connector);
981 return rewrite_assign_rhs(context, result, expr, cond_shape);
984 let expr_rw = expr.rewrite(context, cond_shape);
985 // The expression may (partially) fit on the current line.
986 // We do not allow splitting between `if` and condition.
987 if self.keyword == "if" || expr_rw.is_some() {
991 // The expression won't fit on the current line, jump to next.
992 let nested_shape = shape
993 .block_indent(context.config.tab_spaces())
994 .with_max_width(context.config);
995 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
996 expr.rewrite(context, nested_shape)
997 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
1002 context: &RewriteContext,
1004 alt_block_sep: &str,
1005 ) -> Option<(String, usize)> {
1006 // Do not take the rhs overhead from the upper expressions into account
1007 // when rewriting pattern.
1008 let new_width = context.budget(shape.used_width());
1009 let fresh_shape = Shape {
1013 let constr_shape = if self.nested_if {
1014 // We are part of an if-elseif-else chain. Our constraints are tightened.
1015 // 7 = "} else " .len()
1016 fresh_shape.offset_left(7)?
1021 let label_string = rewrite_label(self.label);
1022 // 1 = space after keyword.
1023 let offset = self.keyword.len() + label_string.len() + 1;
1025 let pat_expr_string = match self.cond {
1026 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
1027 None => String::new(),
1030 let brace_overhead =
1031 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1037 let one_line_budget = context
1040 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1042 let force_newline_brace = (pat_expr_string.contains('\n')
1043 || pat_expr_string.len() > one_line_budget)
1044 && !last_line_extendable(&pat_expr_string);
1046 // Try to format if-else on single line.
1047 if self.allow_single_line
1051 .single_line_if_else_max_width > 0
1053 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1055 if let Some(cond_str) = trial {
1060 .single_line_if_else_max_width
1062 return Some((cond_str, 0));
1067 let cond_span = if let Some(cond) = self.cond {
1070 mk_sp(self.block.span.lo(), self.block.span.lo())
1073 // `for event in event`
1074 // Do not include label in the span.
1075 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1076 let between_kwd_cond = mk_sp(
1079 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1080 if self.pats.is_empty() {
1082 } else if self.matcher.is_empty() {
1083 self.pats[0].span.lo()
1087 .span_before(self.span, self.matcher.trim())
1091 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1093 let after_cond_comment =
1094 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1096 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1098 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1099 || force_newline_brace
1106 let used_width = if pat_expr_string.contains('\n') {
1107 last_line_width(&pat_expr_string)
1109 // 2 = spaces after keyword and condition.
1110 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1118 between_kwd_cond_comment.as_ref().map_or(
1119 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1127 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1134 impl<'a> Rewrite for ControlFlow<'a> {
1135 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1136 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1138 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1139 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1140 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1141 if used_width == 0 {
1142 return Some(cond_str);
1145 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1146 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1147 // we should avoid the single line case.
1148 let block_width = if self.else_block.is_some() || self.nested_if {
1153 let block_shape = Shape {
1157 let mut block_context = context.clone();
1158 block_context.is_if_else_block = self.else_block.is_some();
1160 rewrite_block_with_visitor(&block_context, "", self.block, None, block_shape, true)?;
1162 let mut result = format!("{}{}", cond_str, block_str);
1164 if let Some(else_block) = self.else_block {
1165 let shape = Shape::indented(shape.indent, context.config);
1166 let mut last_in_chain = false;
1167 let rewrite = match else_block.node {
1168 // If the else expression is another if-else expression, prevent it
1169 // from being formatted on a single line.
1170 // Note how we're passing the original shape, as the
1171 // cost of "else" should not cascade.
1172 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1173 ControlFlow::new_if(
1175 ptr_vec_to_ref_vec(pat),
1177 next_else_block.as_ref().map(|e| &**e),
1180 mk_sp(else_block.span.lo(), self.span.hi()),
1181 ).rewrite(context, shape)
1183 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1184 ControlFlow::new_if(
1188 next_else_block.as_ref().map(|e| &**e),
1191 mk_sp(else_block.span.lo(), self.span.hi()),
1192 ).rewrite(context, shape)
1195 last_in_chain = true;
1196 // When rewriting a block, the width is only used for single line
1197 // blocks, passing 1 lets us avoid that.
1198 let else_shape = Shape {
1199 width: min(1, shape.width),
1202 format_expr(else_block, ExprType::Statement, context, else_shape)
1206 let between_kwd_else_block = mk_sp(
1207 self.block.span.hi(),
1210 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1212 let between_kwd_else_block_comment =
1213 extract_comment(between_kwd_else_block, context, shape);
1215 let after_else = mk_sp(
1218 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1219 else_block.span.lo(),
1221 let after_else_comment = extract_comment(after_else, context, shape);
1223 let between_sep = match context.config.control_brace_style() {
1224 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1227 ControlBraceStyle::AlwaysSameLine => " ",
1229 let after_sep = match context.config.control_brace_style() {
1230 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1234 result.push_str(&format!(
1236 between_kwd_else_block_comment
1238 .map_or(between_sep, |s| &**s),
1239 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1241 result.push_str(&rewrite?);
1248 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1250 Some(label) => Cow::from(format!("{}: ", label.ident)),
1251 None => Cow::from(""),
1255 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1256 match rewrite_missing_comment(span, shape, context) {
1257 Some(ref comment) if !comment.is_empty() => Some(format!(
1258 "{indent}{}{indent}",
1260 indent = shape.indent.to_string_with_newline(context.config)
1266 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1267 let snippet = codemap.span_to_snippet(block.span).unwrap();
1268 contains_comment(&snippet)
1271 // Checks that a block contains no statements, an expression and no comments or
1273 // FIXME: incorrectly returns false when comment is contained completely within
1275 pub fn is_simple_block(
1277 attrs: Option<&[ast::Attribute]>,
1280 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1281 && !block_contains_comment(block, codemap) && attrs.map_or(true, |a| a.is_empty()))
1284 /// Checks whether a block contains at most one statement or expression, and no
1285 /// comments or attributes.
1286 pub fn is_simple_block_stmt(
1288 attrs: Option<&[ast::Attribute]>,
1291 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1292 && attrs.map_or(true, |a| a.is_empty())
1295 /// Checks whether a block contains no statements, expressions, comments, or
1296 /// inner attributes.
1297 pub fn is_empty_block(
1299 attrs: Option<&[ast::Attribute]>,
1302 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1303 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1306 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1308 ast::StmtKind::Expr(..) => true,
1313 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1314 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1321 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
1322 struct ArmWrapper<'a> {
1323 pub arm: &'a ast::Arm,
1324 /// True if the arm is the last one in match expression. Used to decide on whether we should add
1325 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
1327 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
1328 pub beginning_vert: Option<BytePos>,
1331 impl<'a> ArmWrapper<'a> {
1335 beginning_vert: Option<BytePos>,
1336 ) -> ArmWrapper<'a> {
1345 impl<'a> Spanned for ArmWrapper<'a> {
1346 fn span(&self) -> Span {
1347 if let Some(lo) = self.beginning_vert {
1348 mk_sp(lo, self.arm.span().hi())
1355 impl<'a> Rewrite for ArmWrapper<'a> {
1356 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1357 rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
1362 context: &RewriteContext,
1367 attrs: &[ast::Attribute],
1368 ) -> Option<String> {
1369 // Do not take the rhs overhead from the upper expressions into account
1370 // when rewriting match condition.
1371 let cond_shape = Shape {
1372 width: context.budget(shape.used_width()),
1376 let cond_shape = match context.config.indent_style() {
1377 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1378 IndentStyle::Block => cond_shape.offset_left(6)?,
1380 let cond_str = cond.rewrite(context, cond_shape)?;
1381 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1382 let block_sep = match context.config.control_brace_style() {
1383 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1384 _ if last_line_extendable(&cond_str) => " ",
1386 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
1390 let nested_indent_str = shape
1392 .block_indent(context.config)
1393 .to_string(context.config);
1394 // Inner attributes.
1395 let inner_attrs = &inner_attributes(attrs);
1396 let inner_attrs_str = if inner_attrs.is_empty() {
1400 .rewrite(context, shape)
1401 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1404 let open_brace_pos = if inner_attrs.is_empty() {
1405 let hi = if arms.is_empty() {
1412 .span_after(mk_sp(cond.span.hi(), hi), "{")
1414 inner_attrs[inner_attrs.len() - 1].span().hi()
1417 if arms.is_empty() {
1418 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1419 if snippet.trim().is_empty() {
1420 Some(format!("match {} {{}}", cond_str))
1422 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1423 Some(context.snippet(span).to_owned())
1427 "match {}{}{{\n{}{}{}\n{}}}",
1432 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1433 shape.indent.to_string(context.config),
1438 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1439 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1441 } else if config.match_block_trailing_comma() {
1443 } else if let ast::ExprKind::Block(ref block) = body.node {
1444 if let ast::BlockCheckMode::Default = block.rules {
1454 /// Collect a byte position of the beginning `|` for each arm, if available.
1455 fn collect_beginning_verts(
1456 context: &RewriteContext,
1459 ) -> Vec<Option<BytePos>> {
1460 let mut beginning_verts = Vec::with_capacity(arms.len());
1461 let mut lo = context.snippet_provider.span_after(span, "{");
1463 let hi = arm.pats[0].span.lo();
1464 let missing_span = mk_sp(lo, hi);
1465 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
1466 lo = arm.span().hi();
1471 fn rewrite_match_arms(
1472 context: &RewriteContext,
1476 open_brace_pos: BytePos,
1477 ) -> Option<String> {
1478 let arm_shape = shape
1479 .block_indent(context.config.tab_spaces())
1480 .with_max_width(context.config);
1482 let arm_len = arms.len();
1483 let is_last_iter = repeat(false)
1484 .take(arm_len.checked_sub(1).unwrap_or(0))
1485 .chain(repeat(true));
1486 let beginning_verts = collect_beginning_verts(context, arms, span);
1487 let items = itemize_list(
1488 context.snippet_provider,
1491 .zip(beginning_verts.into_iter())
1492 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
1495 |arm| arm.span().lo(),
1496 |arm| arm.span().hi(),
1497 |arm| arm.rewrite(context, arm_shape),
1502 let arms_vec: Vec<_> = items.collect();
1503 let fmt = ListFormatting {
1504 tactic: DefinitiveListTactic::Vertical,
1505 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1507 trailing_separator: SeparatorTactic::Never,
1508 separator_place: SeparatorPlace::Back,
1510 ends_with_newline: true,
1511 preserve_newline: true,
1512 config: context.config,
1515 write_list(&arms_vec, &fmt)
1518 fn rewrite_match_arm(
1519 context: &RewriteContext,
1523 beginning_vert: Option<BytePos>,
1524 ) -> Option<String> {
1525 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1526 if contains_skip(&arm.attrs) {
1527 let (_, body) = flatten_arm_body(context, &arm.body);
1528 // `arm.span()` does not include trailing comma, add it manually.
1529 return Some(format!(
1531 context.snippet(arm.span()),
1532 arm_comma(context.config, body, is_last),
1535 let missing_span = mk_sp(
1536 arm.attrs[arm.attrs.len() - 1].span.hi(),
1537 arm.pats[0].span.lo(),
1539 (missing_span, arm.attrs.rewrite(context, shape)?)
1541 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1543 let pats_str = rewrite_match_pattern(
1545 &ptr_vec_to_ref_vec(&arm.pats),
1547 beginning_vert.is_some(),
1549 ).and_then(|pats_str| {
1550 combine_strs_with_missing_comments(
1564 arm.guard.is_some(),
1569 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
1573 /// - `&[single-line, ntp]`
1576 /// - `[small, ntp]`
1577 /// - unary tuple constructor `([small, ntp])`
1579 fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
1580 // We also require that the pattern is reasonably 'small' with its literal width.
1581 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
1584 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
1586 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
1587 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
1588 ast::PatKind::Struct(..)
1589 | ast::PatKind::Mac(..)
1590 | ast::PatKind::Slice(..)
1591 | ast::PatKind::Path(..)
1592 | ast::PatKind::Range(..) => false,
1593 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
1594 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
1595 path.segments.len() <= 1 && subpats.len() <= 1
1597 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
1598 is_short_pattern_inner(&*p)
1603 fn rewrite_match_pattern(
1604 context: &RewriteContext,
1606 guard: &Option<ptr::P<ast::Expr>>,
1607 has_beginning_vert: bool,
1609 ) -> Option<String> {
1613 let pat_shape = shape
1615 .offset_left(if has_beginning_vert { 2 } else { 0 })?;
1616 let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
1617 let beginning_vert = if has_beginning_vert { "| " } else { "" };
1620 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1622 Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
1626 // @extend: true if the arm body can be put next to `=>`
1627 // @body: flattened body, if the body is block with a single expression
1628 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1630 ast::ExprKind::Block(ref block)
1631 if !is_unsafe_block(block)
1632 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
1634 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1636 !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
1644 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
1650 fn rewrite_match_body(
1651 context: &RewriteContext,
1652 body: &ptr::P<ast::Expr>,
1657 ) -> Option<String> {
1658 let (extend, body) = flatten_arm_body(context, body);
1659 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1662 is_empty_block(block, Some(&body.attrs), context.codemap),
1668 let comma = arm_comma(context.config, body, is_last);
1669 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1671 let combine_orig_body = |body_str: &str| {
1672 let block_sep = match context.config.control_brace_style() {
1673 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1677 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1680 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1681 let next_line_indent = if !is_block || is_empty_block {
1682 shape.indent.block_indent(context.config)
1686 let combine_next_line_body = |body_str: &str| {
1688 return Some(format!(
1691 next_line_indent.to_string_with_newline(context.config),
1696 let indent_str = shape.indent.to_string_with_newline(context.config);
1697 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
1698 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
1699 let comma = if context.config.match_block_trailing_comma() {
1704 ("{", format!("{}}}{}", indent_str, comma))
1706 ("", String::from(","))
1709 let block_sep = match context.config.control_brace_style() {
1710 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
1711 _ if body_prefix.is_empty() => "".to_owned(),
1712 _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
1713 _ => format!(" {}", body_prefix),
1714 } + &nested_indent_str;
1718 pats_str, block_sep, body_str, body_suffix
1722 // Let's try and get the arm body on the same line as the condition.
1724 let orig_body_shape = shape
1725 .offset_left(extra_offset(pats_str, shape) + 4)
1726 .and_then(|shape| shape.sub_width(comma.len()));
1727 let orig_body = if let Some(body_shape) = orig_body_shape {
1728 let rewrite = nop_block_collapse(
1729 format_expr(body, ExprType::Statement, context, body_shape),
1735 if !forbid_same_line
1737 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1739 return combine_orig_body(body_str);
1746 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1748 // Try putting body on the next line and see if it looks better.
1749 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1750 let next_line_body = nop_block_collapse(
1751 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1752 next_line_body_shape.width,
1754 match (orig_body, next_line_body) {
1755 (Some(ref orig_str), Some(ref next_line_str))
1757 || prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
1759 combine_next_line_body(next_line_str)
1761 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1762 combine_orig_body(orig_str)
1764 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1765 combine_next_line_body(next_line_str)
1767 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1768 (None, None) => None,
1769 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1773 // The `if ...` guard on a match arm.
1775 context: &RewriteContext,
1776 guard: &Option<ptr::P<ast::Expr>>,
1778 // The amount of space used up on this line for the pattern in
1779 // the arm (excludes offset).
1780 pattern_width: usize,
1781 ) -> Option<String> {
1782 if let Some(ref guard) = *guard {
1783 // First try to fit the guard string on the same line as the pattern.
1784 // 4 = ` if `, 5 = ` => {`
1785 let cond_shape = shape
1786 .offset_left(pattern_width + 4)
1787 .and_then(|s| s.sub_width(5));
1788 if let Some(cond_shape) = cond_shape {
1789 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1790 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1791 return Some(format!(" if {}", cond_str));
1796 // Not enough space to put the guard after the pattern, try a newline.
1797 // 3 = `if `, 5 = ` => {`
1798 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1800 .and_then(|s| s.sub_width(5));
1801 if let Some(cond_shape) = cond_shape {
1802 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1803 return Some(format!(
1805 cond_shape.indent.to_string_with_newline(context.config),
1817 fn rewrite_multiple_patterns(
1818 context: &RewriteContext,
1821 ) -> Option<String> {
1822 let pat_strs = pats.iter()
1823 .map(|p| p.rewrite(context, shape))
1824 .collect::<Option<Vec<_>>>()?;
1826 let use_mixed_layout = pats.iter()
1827 .zip(pat_strs.iter())
1828 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1829 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1830 let tactic = if use_mixed_layout {
1831 DefinitiveListTactic::Mixed
1835 ListTactic::HorizontalVertical,
1836 Separator::VerticalBar,
1840 let fmt = ListFormatting {
1843 trailing_separator: SeparatorTactic::Never,
1844 separator_place: context.config.binop_separator(),
1846 ends_with_newline: false,
1847 preserve_newline: false,
1848 config: context.config,
1850 write_list(&items, &fmt)
1853 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
1855 // We do not allow `if` to stay on the same line, since we could easily mistake
1856 // `pat => if cond { ... }` and `pat if cond => { ... }`.
1857 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
1858 ast::ExprKind::ForLoop(..)
1859 | ast::ExprKind::Loop(..)
1860 | ast::ExprKind::While(..)
1861 | ast::ExprKind::WhileLet(..)
1862 | ast::ExprKind::Match(..)
1863 | ast::ExprKind::Block(..)
1864 | ast::ExprKind::Closure(..)
1865 | ast::ExprKind::Array(..)
1866 | ast::ExprKind::Call(..)
1867 | ast::ExprKind::MethodCall(..)
1868 | ast::ExprKind::Mac(..)
1869 | ast::ExprKind::Struct(..)
1870 | ast::ExprKind::Tup(..) => true,
1871 ast::ExprKind::AddrOf(_, ref expr)
1872 | ast::ExprKind::Box(ref expr)
1873 | ast::ExprKind::Try(ref expr)
1874 | ast::ExprKind::Unary(_, ref expr)
1875 | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
1880 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1882 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1884 context.snippet(l.span).to_owned(),
1885 context.config.max_width(),
1891 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1892 let string_lit = context.snippet(span);
1894 if !context.config.format_strings() {
1899 .all(|line| line.ends_with('\\'))
1901 let new_indent = shape.visual_indent(1).indent;
1902 let indented_string_lit = String::from(
1908 new_indent.to_string(context.config),
1912 .collect::<Vec<_>>()
1916 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1918 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1922 // Remove the quote characters.
1923 let str_lit = &string_lit[1..string_lit.len() - 1];
1927 &StringFormat::new(shape.visual_indent(0), context.config),
1932 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1933 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1934 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1936 .find(|&&(s, _)| s == callee_str)
1938 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1940 Some((all_simple, num_args_before))
1946 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1949 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1950 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1951 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1952 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1953 // format! like macros
1954 // From the Rust Standard Library.
1958 ("format_args!", 0),
1962 ("unreachable!", 0),
1963 // From the `log` crate.
1968 // write! like macros
1970 ("debug_assert!", 1),
1973 // assert_eq! like macros
1976 ("debug_assert_eq!", 2),
1977 ("debug_assert_ne!", 2),
1980 pub fn rewrite_call(
1981 context: &RewriteContext,
1983 args: &[ptr::P<ast::Expr>],
1986 ) -> Option<String> {
1987 overflow::rewrite_with_parens(
1990 &ptr_vec_to_ref_vec(args),
1993 context.config.width_heuristics().fn_call_width,
1994 if context.inside_macro {
1995 if span_ends_with_comma(context, span) {
1996 Some(SeparatorTactic::Always)
1998 Some(SeparatorTactic::Never)
2006 fn is_simple_expr(expr: &ast::Expr) -> bool {
2008 ast::ExprKind::Lit(..) => true,
2009 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
2010 ast::ExprKind::AddrOf(_, ref expr)
2011 | ast::ExprKind::Box(ref expr)
2012 | ast::ExprKind::Cast(ref expr, _)
2013 | ast::ExprKind::Field(ref expr, _)
2014 | ast::ExprKind::Try(ref expr)
2015 | ast::ExprKind::TupField(ref expr, _)
2016 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
2017 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
2018 is_simple_expr(lhs) && is_simple_expr(rhs)
2024 fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
2027 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
2030 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2032 ast::ExprKind::Match(..) => {
2033 (context.use_block_indent() && args_len == 1)
2034 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
2036 ast::ExprKind::If(..)
2037 | ast::ExprKind::IfLet(..)
2038 | ast::ExprKind::ForLoop(..)
2039 | ast::ExprKind::Loop(..)
2040 | ast::ExprKind::While(..)
2041 | ast::ExprKind::WhileLet(..) => {
2042 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2044 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2045 context.use_block_indent()
2046 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
2048 ast::ExprKind::Array(..)
2049 | ast::ExprKind::Call(..)
2050 | ast::ExprKind::Mac(..)
2051 | ast::ExprKind::MethodCall(..)
2052 | ast::ExprKind::Struct(..)
2053 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2054 ast::ExprKind::AddrOf(_, ref expr)
2055 | ast::ExprKind::Box(ref expr)
2056 | ast::ExprKind::Try(ref expr)
2057 | ast::ExprKind::Unary(_, ref expr)
2058 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2063 pub fn is_nested_call(expr: &ast::Expr) -> bool {
2065 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
2066 ast::ExprKind::AddrOf(_, ref expr)
2067 | ast::ExprKind::Box(ref expr)
2068 | ast::ExprKind::Try(ref expr)
2069 | ast::ExprKind::Unary(_, ref expr)
2070 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
2075 /// Return true if a function call or a method call represented by the given span ends with a
2076 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2077 /// comma from macro can potentially break the code.
2078 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2079 let mut result: bool = Default::default();
2080 let mut prev_char: char = Default::default();
2082 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
2084 _ if kind.is_comment() || c.is_whitespace() => continue,
2085 ')' | '}' => result = result && prev_char != c,
2086 ',' => result = true,
2087 _ => result = false,
2096 context: &RewriteContext,
2097 mut subexpr: &ast::Expr,
2100 ) -> Option<String> {
2101 debug!("rewrite_paren, shape: {:?}", shape);
2103 // Extract comments within parens.
2104 let mut pre_comment;
2105 let mut post_comment;
2108 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
2109 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
2110 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
2111 post_comment = rewrite_missing_comment(post_span, shape, context)?;
2113 // Remove nested parens if there are no comments.
2114 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
2115 if pre_comment.is_empty() && post_comment.is_empty() {
2116 span = subexpr.span;
2117 subexpr = subsubexpr;
2125 let total_paren_overhead = paren_overhead(context);
2126 let paren_overhead = total_paren_overhead / 2;
2127 let sub_shape = shape
2128 .offset_left(paren_overhead)
2129 .and_then(|s| s.sub_width(paren_overhead))?;
2131 let paren_wrapper = |s: &str| {
2132 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2133 format!("( {}{}{} )", pre_comment, s, post_comment)
2135 format!("({}{}{})", pre_comment, s, post_comment)
2139 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2140 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2142 if subexpr_str.contains('\n')
2143 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2145 Some(paren_wrapper(&subexpr_str))
2154 context: &RewriteContext,
2156 ) -> Option<String> {
2157 let expr_str = expr.rewrite(context, shape)?;
2159 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2165 let offset = last_line_width(&expr_str) + lbr.len();
2166 let rhs_overhead = shape.rhs_overhead(context.config);
2167 let index_shape = if expr_str.contains('\n') {
2168 Shape::legacy(context.config.max_width(), shape.indent)
2169 .offset_left(offset)
2170 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2172 shape.visual_indent(offset).sub_width(offset + rbr.len())
2174 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2176 // Return if index fits in a single line.
2177 match orig_index_rw {
2178 Some(ref index_str) if !index_str.contains('\n') => {
2179 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2184 // Try putting index on the next line and see if it fits in a single line.
2185 let indent = shape.indent.block_indent(context.config);
2186 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2187 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2188 let new_index_rw = index.rewrite(context, index_shape);
2189 match (orig_index_rw, new_index_rw) {
2190 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2193 indent.to_string_with_newline(context.config),
2198 (None, Some(ref new_index_str)) => Some(format!(
2201 indent.to_string_with_newline(context.config),
2206 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2211 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2216 fields.iter().all(|field| !field.is_shorthand)
2219 fn rewrite_struct_lit<'a>(
2220 context: &RewriteContext,
2222 fields: &'a [ast::Field],
2223 base: Option<&'a ast::Expr>,
2226 ) -> Option<String> {
2227 debug!("rewrite_struct_lit: shape {:?}", shape);
2229 enum StructLitField<'a> {
2230 Regular(&'a ast::Field),
2231 Base(&'a ast::Expr),
2235 let path_shape = shape.sub_width(2)?;
2236 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2238 if fields.is_empty() && base.is_none() {
2239 return Some(format!("{} {{}}", path_str));
2242 // Foo { a: Foo } - indent is +3, width is -5.
2243 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2245 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2246 let body_lo = context.snippet_provider.span_after(span, "{");
2247 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2248 && context.config.struct_field_align_threshold() > 0
2250 rewrite_with_alignment(
2254 mk_sp(body_lo, span.hi()),
2258 let field_iter = fields
2260 .map(StructLitField::Regular)
2261 .chain(base.into_iter().map(StructLitField::Base));
2263 let span_lo = |item: &StructLitField| match *item {
2264 StructLitField::Regular(field) => field.span().lo(),
2265 StructLitField::Base(expr) => {
2266 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2267 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2268 let pos = snippet.find_uncommented("..").unwrap();
2269 last_field_hi + BytePos(pos as u32)
2272 let span_hi = |item: &StructLitField| match *item {
2273 StructLitField::Regular(field) => field.span().hi(),
2274 StructLitField::Base(expr) => expr.span.hi(),
2276 let rewrite = |item: &StructLitField| match *item {
2277 StructLitField::Regular(field) => {
2278 // The 1 taken from the v_budget is for the comma.
2279 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2281 StructLitField::Base(expr) => {
2283 expr.rewrite(context, v_shape.offset_left(2)?)
2284 .map(|s| format!("..{}", s))
2288 let items = itemize_list(
2289 context.snippet_provider,
2300 let item_vec = items.collect::<Vec<_>>();
2302 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2303 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2305 let ends_with_comma = span_ends_with_comma(context, span);
2306 let force_no_trailing_comma = if context.inside_macro && !ends_with_comma {
2312 let fmt = struct_lit_formatting(
2316 force_no_trailing_comma || base.is_some(),
2319 write_list(&item_vec, &fmt)?
2322 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2323 Some(format!("{} {{{}}}", path_str, fields_str))
2325 // FIXME if context.config.indent_style() == Visual, but we run out
2326 // of space, we should fall back to BlockIndent.
2329 pub fn wrap_struct_field(
2330 context: &RewriteContext,
2333 nested_shape: Shape,
2334 one_line_width: usize,
2336 if context.config.indent_style() == IndentStyle::Block
2337 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
2338 || fields_str.len() > one_line_width)
2342 nested_shape.indent.to_string_with_newline(context.config),
2344 shape.indent.to_string_with_newline(context.config)
2347 // One liner or visual indent.
2348 format!(" {} ", fields_str)
2352 pub fn struct_lit_field_separator(config: &Config) -> &str {
2353 colon_spaces(config.space_before_colon(), config.space_after_colon())
2356 pub fn rewrite_field(
2357 context: &RewriteContext,
2360 prefix_max_width: usize,
2361 ) -> Option<String> {
2362 if contains_skip(&field.attrs) {
2363 return Some(context.snippet(field.span()).to_owned());
2365 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2366 if !attrs_str.is_empty() {
2367 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
2369 let name = field.ident.node.to_string();
2370 if field.is_shorthand {
2371 Some(attrs_str + &name)
2373 let mut separator = String::from(struct_lit_field_separator(context.config));
2374 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2375 separator.push(' ');
2377 let overhead = name.len() + separator.len();
2378 let expr_shape = shape.offset_left(overhead)?;
2379 let expr = field.expr.rewrite(context, expr_shape);
2382 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
2383 Some(attrs_str + &name)
2385 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2387 let expr_offset = shape.indent.block_indent(context.config);
2390 .rewrite(context, Shape::indented(expr_offset, context.config));
2396 expr_offset.to_string(context.config),
2405 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2406 context: &RewriteContext,
2412 T: Rewrite + Spanned + ToExpr + 'a,
2414 let mut items = items.iter();
2415 // In case of length 1, need a trailing comma
2416 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2417 if items.len() == 1 {
2419 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2423 .rewrite(context, nested_shape)
2425 if context.config.spaces_within_parens_and_brackets() {
2426 format!("( {}, )", s)
2433 let list_lo = context.snippet_provider.span_after(span, "(");
2434 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2435 let items = itemize_list(
2436 context.snippet_provider,
2440 |item| item.span().lo(),
2441 |item| item.span().hi(),
2442 |item| item.rewrite(context, nested_shape),
2444 span.hi() - BytePos(1),
2447 let item_vec: Vec<_> = items.collect();
2448 let tactic = definitive_tactic(
2450 ListTactic::HorizontalVertical,
2454 let fmt = ListFormatting {
2457 trailing_separator: SeparatorTactic::Never,
2458 separator_place: SeparatorPlace::Back,
2460 ends_with_newline: false,
2461 preserve_newline: false,
2462 config: context.config,
2464 let list_str = write_list(&item_vec, &fmt)?;
2466 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2467 Some(format!("( {} )", list_str))
2469 Some(format!("({})", list_str))
2473 pub fn rewrite_tuple<'a, T>(
2474 context: &RewriteContext,
2480 T: Rewrite + Spanned + ToExpr + 'a,
2482 debug!("rewrite_tuple {:?}", shape);
2483 if context.use_block_indent() {
2484 // We use the same rule as function calls for rewriting tuples.
2485 let force_tactic = if context.inside_macro {
2486 if span_ends_with_comma(context, span) {
2487 Some(SeparatorTactic::Always)
2489 Some(SeparatorTactic::Never)
2492 if items.len() == 1 {
2493 Some(SeparatorTactic::Always)
2498 overflow::rewrite_with_parens(
2504 context.config.width_heuristics().fn_call_width,
2508 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2512 pub fn rewrite_unary_prefix<R: Rewrite>(
2513 context: &RewriteContext,
2517 ) -> Option<String> {
2519 .rewrite(context, shape.offset_left(prefix.len())?)
2520 .map(|r| format!("{}{}", prefix, r))
2523 // FIXME: this is probably not correct for multi-line Rewrites. we should
2524 // subtract suffix.len() from the last line budget, not the first!
2525 pub fn rewrite_unary_suffix<R: Rewrite>(
2526 context: &RewriteContext,
2530 ) -> Option<String> {
2532 .rewrite(context, shape.sub_width(suffix.len())?)
2539 fn rewrite_unary_op(
2540 context: &RewriteContext,
2544 ) -> Option<String> {
2545 // For some reason, an UnOp is not spanned like BinOp!
2546 let operator_str = match *op {
2547 ast::UnOp::Deref => "*",
2548 ast::UnOp::Not => "!",
2549 ast::UnOp::Neg => "-",
2551 rewrite_unary_prefix(context, operator_str, expr, shape)
2554 fn rewrite_assignment(
2555 context: &RewriteContext,
2558 op: Option<&ast::BinOp>,
2560 ) -> Option<String> {
2561 let operator_str = match op {
2562 Some(op) => context.snippet(op.span),
2566 // 1 = space between lhs and operator.
2567 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2568 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2570 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2573 /// Controls where to put the rhs.
2574 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2575 pub enum RhsTactics {
2578 /// Put the rhs on the next line if it uses multiple line.
2582 // The left hand side must contain everything up to, and including, the
2583 // assignment operator.
2584 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2585 context: &RewriteContext,
2589 ) -> Option<String> {
2590 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
2593 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2594 context: &RewriteContext,
2598 rhs_tactics: RhsTactics,
2599 ) -> Option<String> {
2600 let lhs = lhs.into();
2601 let last_line_width = last_line_width(&lhs)
2602 .checked_sub(if lhs.contains('\n') {
2603 shape.indent.width()
2608 // 1 = space between operator and rhs.
2609 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2611 offset: shape.offset + last_line_width + 1,
2614 let rhs = choose_rhs(
2618 ex.rewrite(context, orig_shape),
2624 fn choose_rhs<R: Rewrite>(
2625 context: &RewriteContext,
2628 orig_rhs: Option<String>,
2629 rhs_tactics: RhsTactics,
2630 ) -> Option<String> {
2632 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2633 Some(format!(" {}", new_str))
2636 // Expression did not fit on the same line as the identifier.
2637 // Try splitting the line and see if that works better.
2639 Shape::indented(shape.indent.block_indent(context.config), context.config)
2640 .sub_width(shape.rhs_overhead(context.config))?;
2641 let new_rhs = expr.rewrite(context, new_shape);
2642 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2644 match (orig_rhs, new_rhs) {
2645 (Some(ref orig_rhs), Some(ref new_rhs))
2646 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2649 Some(format!(" {}", orig_rhs))
2651 (Some(ref orig_rhs), Some(ref new_rhs))
2652 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2654 Some(format!("{}{}", new_indent_str, new_rhs))
2656 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2657 (None, None) => None,
2658 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2664 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2665 rhs_tactics == RhsTactics::ForceNextLine || !next_line_rhs.contains('\n')
2666 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2669 fn rewrite_expr_addrof(
2670 context: &RewriteContext,
2671 mutability: ast::Mutability,
2674 ) -> Option<String> {
2675 let operator_str = match mutability {
2676 ast::Mutability::Immutable => "&",
2677 ast::Mutability::Mutable => "&mut ",
2679 rewrite_unary_prefix(context, operator_str, expr, shape)
2683 fn to_expr(&self) -> Option<&ast::Expr>;
2684 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2687 impl ToExpr for ast::Expr {
2688 fn to_expr(&self) -> Option<&ast::Expr> {
2692 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2693 can_be_overflowed_expr(context, self, len)
2697 impl ToExpr for ast::Ty {
2698 fn to_expr(&self) -> Option<&ast::Expr> {
2702 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2703 can_be_overflowed_type(context, self, len)
2707 impl<'a> ToExpr for TuplePatField<'a> {
2708 fn to_expr(&self) -> Option<&ast::Expr> {
2712 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2713 can_be_overflowed_pat(context, self, len)
2717 impl<'a> ToExpr for ast::StructField {
2718 fn to_expr(&self) -> Option<&ast::Expr> {
2722 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2727 impl<'a> ToExpr for MacroArg {
2728 fn to_expr(&self) -> Option<&ast::Expr> {
2730 MacroArg::Expr(ref expr) => Some(expr),
2735 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2737 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2738 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2739 MacroArg::Pat(..) => false,
2740 MacroArg::Item(..) => len == 1,
2745 impl ToExpr for ast::GenericParam {
2746 fn to_expr(&self) -> Option<&ast::Expr> {
2750 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {