1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use std::iter::{repeat, ExactSizeIterator};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
19 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23 rewrite_comment, rewrite_missing_comment, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
28 use macros::{rewrite_macro, MacroArg, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
32 use string::{rewrite_string, StringFormat};
33 use types::{can_be_overflowed_type, rewrite_path, PathContext};
34 use utils::{colon_spaces, contains_skip, extra_offset, first_line_width, inner_attributes,
35 last_line_extendable, last_line_width, mk_sp, outer_attributes, paren_overhead,
36 ptr_vec_to_ref_vec, semicolon_for_stmt, trimmed_last_line_width, wrap_str};
37 use vertical::rewrite_with_alignment;
38 use visitor::FmtVisitor;
40 impl Rewrite for ast::Expr {
41 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
42 format_expr(self, ExprType::SubExpression, context, shape)
46 #[derive(Copy, Clone, PartialEq)]
55 context: &RewriteContext,
58 skip_out_of_file_lines_range!(context, expr.span);
60 if contains_skip(&*expr.attrs) {
61 return Some(context.snippet(expr.span()));
64 let expr_rw = match expr.node {
65 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
66 expr_vec.iter().map(|e| &**e),
67 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
72 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
73 ast::ExprKind::Call(ref callee, ref args) => {
74 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
75 let callee_str = callee.rewrite(context, shape)?;
76 rewrite_call(context, &callee_str, args, inner_span, shape)
78 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
79 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
80 // FIXME: format comments between operands and operator
84 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
87 context.config.binop_separator(),
90 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
91 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
95 base.as_ref().map(|e| &**e),
99 ast::ExprKind::Tup(ref items) => {
100 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
102 ast::ExprKind::If(..) |
103 ast::ExprKind::IfLet(..) |
104 ast::ExprKind::ForLoop(..) |
105 ast::ExprKind::Loop(..) |
106 ast::ExprKind::While(..) |
107 ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
108 .and_then(|control_flow| control_flow.rewrite(context, shape)),
109 ast::ExprKind::Block(ref block) => {
111 ExprType::Statement => {
112 if is_unsafe_block(block) {
113 block.rewrite(context, shape)
114 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
115 // Rewrite block without trying to put it in a single line.
118 let prefix = block_prefix(context, block, shape)?;
119 rewrite_block_with_visitor(context, &prefix, block, shape)
122 ExprType::SubExpression => block.rewrite(context, shape),
125 ast::ExprKind::Match(ref cond, ref arms) => {
126 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
128 ast::ExprKind::Path(ref qself, ref path) => {
129 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
131 ast::ExprKind::Assign(ref lhs, ref rhs) => {
132 rewrite_assignment(context, lhs, rhs, None, shape)
134 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
135 rewrite_assignment(context, lhs, rhs, Some(op), shape)
137 ast::ExprKind::Continue(ref opt_ident) => {
138 let id_str = match *opt_ident {
139 Some(ident) => format!(" {}", ident.node),
140 None => String::new(),
142 Some(format!("continue{}", id_str))
144 ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
145 let id_str = match *opt_ident {
146 Some(ident) => format!(" {}", ident.node),
147 None => String::new(),
150 if let Some(ref expr) = *opt_expr {
151 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
153 Some(format!("break{}", id_str))
156 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
157 rewrite_unary_prefix(context, "yield ", &**expr, shape)
159 Some("yield".to_string())
161 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
162 closures::rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
164 ast::ExprKind::Try(..) |
165 ast::ExprKind::Field(..) |
166 ast::ExprKind::TupField(..) |
167 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
168 ast::ExprKind::Mac(ref mac) => {
169 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
171 context.snippet(expr.span),
172 context.config.max_width(),
177 ast::ExprKind::Ret(None) => Some("return".to_owned()),
178 ast::ExprKind::Ret(Some(ref expr)) => {
179 rewrite_unary_prefix(context, "return ", &**expr, shape)
181 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
182 ast::ExprKind::AddrOf(mutability, ref expr) => {
183 rewrite_expr_addrof(context, mutability, expr, shape)
185 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
188 PairParts::new("", " as ", ""),
191 SeparatorPlace::Front,
193 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
196 PairParts::new("", ": ", ""),
199 SeparatorPlace::Back,
201 ast::ExprKind::Index(ref expr, ref index) => {
202 rewrite_index(&**expr, &**index, context, shape)
204 ast::ExprKind::Repeat(ref expr, ref repeats) => {
205 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
213 PairParts::new(lbr, "; ", rbr),
216 SeparatorPlace::Back,
219 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
220 let delim = match limits {
221 ast::RangeLimits::HalfOpen => "..",
222 ast::RangeLimits::Closed => "..=",
225 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
227 ast::ExprKind::Lit(ref lit) => match lit.node {
228 ast::LitKind::FloatUnsuffixed(..) => {
229 context.snippet(lit.span).ends_with('.')
237 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
238 (Some(lhs), Some(rhs)) => {
239 let sp_delim = if context.config.spaces_around_ranges() {
240 format!(" {} ", delim)
241 } else if needs_space_before_range(context, lhs) {
242 format!(" {}", delim)
249 PairParts::new("", &sp_delim, ""),
252 SeparatorPlace::Front,
255 (None, Some(rhs)) => {
256 let sp_delim = if context.config.spaces_around_ranges() {
257 format!("{} ", delim)
261 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
263 (Some(lhs), None) => {
264 let sp_delim = if context.config.spaces_around_ranges() {
265 format!(" {}", delim)
269 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
271 (None, None) => Some(delim.into()),
274 // We do not format these expressions yet, but they should still
275 // satisfy our width restrictions.
276 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
277 Some(context.snippet(expr.span))
279 ast::ExprKind::Catch(ref block) => {
280 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
284 let budget = shape.width.checked_sub(9).unwrap_or(0);
288 block.rewrite(context, Shape::legacy(budget, shape.indent))?
295 .and_then(|expr_str| {
296 recover_comment_removed(expr_str, expr.span, context)
298 .and_then(|expr_str| {
299 let attrs = outer_attributes(&expr.attrs);
300 let attrs_str = attrs.rewrite(context, shape)?;
302 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
305 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
310 pub struct PairParts<'a> {
316 pub fn rewrite_pair<LHS, RHS>(
320 context: &RewriteContext,
322 separator_place: SeparatorPlace,
328 let lhs_overhead = match separator_place {
329 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
330 SeparatorPlace::Front => shape.used_width(),
332 let lhs_shape = Shape {
333 width: context.budget(lhs_overhead),
336 let lhs_result = lhs.rewrite(context, lhs_shape)
337 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
339 // Try to the both lhs and rhs on the same line.
340 let rhs_orig_result = shape
341 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
342 .and_then(|s| s.sub_width(pp.suffix.len()))
343 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
344 if let Some(ref rhs_result) = rhs_orig_result {
345 // If the rhs looks like block expression, we allow it to stay on the same line
346 // with the lhs even if it is multi-lined.
347 let allow_same_line = rhs_result
350 .map(|first_line| first_line.ends_with('{'))
352 if !rhs_result.contains('\n') || allow_same_line {
353 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
354 + first_line_width(rhs_result) + pp.suffix.len();
355 if one_line_width <= shape.width {
367 // We have to use multiple lines.
368 // Re-evaluate the rhs because we have more space now:
369 let mut rhs_shape = match context.config.indent_style() {
370 IndentStyle::Visual => shape
371 .sub_width(pp.suffix.len() + pp.prefix.len())?
372 .visual_indent(pp.prefix.len()),
373 IndentStyle::Block => {
374 // Try to calculate the initial constraint on the right hand side.
375 let rhs_overhead = shape.rhs_overhead(context.config);
376 Shape::indented(shape.indent.block_indent(context.config), context.config)
377 .sub_width(rhs_overhead)?
380 let infix = match separator_place {
381 SeparatorPlace::Back => pp.infix.trim_right(),
382 SeparatorPlace::Front => pp.infix.trim_left(),
384 if separator_place == SeparatorPlace::Front {
385 rhs_shape = rhs_shape.offset_left(infix.len())?;
387 let rhs_result = rhs.rewrite(context, rhs_shape)?;
388 let indent_str = rhs_shape.indent.to_string(context.config);
389 let infix_with_sep = match separator_place {
390 SeparatorPlace::Back => format!("{}\n{}", infix, indent_str),
391 SeparatorPlace::Front => format!("\n{}{}", indent_str, infix),
402 pub fn rewrite_array<'a, I>(
405 context: &RewriteContext,
407 trailing_comma: bool,
410 I: Iterator<Item = &'a ast::Expr>,
412 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
418 let nested_shape = match context.config.indent_style() {
419 IndentStyle::Block => shape
421 .block_indent(context.config.tab_spaces())
422 .with_max_width(context.config)
424 IndentStyle::Visual => shape
425 .visual_indent(bracket_size)
426 .sub_width(bracket_size * 2)?,
429 let items = itemize_list(
433 |item| item.span.lo(),
434 |item| item.span.hi(),
435 |item| item.rewrite(context, nested_shape),
439 ).collect::<Vec<_>>();
441 if items.is_empty() {
442 if context.config.spaces_within_parens_and_brackets() {
443 return Some("[ ]".to_string());
445 return Some("[]".to_string());
449 let has_long_item = items
451 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
453 let mut tactic = match context.config.indent_style() {
454 IndentStyle::Block => {
455 // FIXME wrong shape in one-line case
456 match shape.width.checked_sub(2 * bracket_size) {
459 ListTactic::LimitedHorizontalVertical(context.config.array_width());
460 definitive_tactic(&items, tactic, Separator::Comma, width)
462 None => DefinitiveListTactic::Vertical,
465 IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
468 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
473 DefinitiveListTactic::Mixed
476 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
477 if context.config.array_horizontal_layout_threshold() > 0
478 && items.len() > context.config.array_horizontal_layout_threshold()
480 tactic = DefinitiveListTactic::Mixed;
483 let fmt = ListFormatting {
486 trailing_separator: if trailing_comma {
487 SeparatorTactic::Always
488 } else if context.inside_macro || context.config.indent_style() == IndentStyle::Visual {
489 SeparatorTactic::Never
491 SeparatorTactic::Vertical
493 separator_place: SeparatorPlace::Back,
495 ends_with_newline: ends_with_newline,
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(context.config),
514 shape.block().indent.to_string(context.config)
521 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
522 debug!("nop_block_collapse {:?} {}", block_str, budget);
523 block_str.map(|block_str| {
524 if block_str.starts_with('{') && budget >= 2
525 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
534 fn rewrite_empty_block(
535 context: &RewriteContext,
538 ) -> Option<String> {
539 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
541 return Some("{}".to_owned());
544 // If a block contains only a single-line comment, then leave it on one line.
545 let user_str = context.snippet(block.span);
546 let user_str = user_str.trim();
547 if user_str.starts_with('{') && user_str.ends_with('}') {
548 let comment_str = user_str[1..user_str.len() - 1].trim();
549 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
550 && comment_str.len() + 4 <= shape.width
552 return Some(format!("{{ {} }}", comment_str));
559 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
560 Some(match block.rules {
561 ast::BlockCheckMode::Unsafe(..) => {
562 let snippet = context.snippet(block.span);
563 let open_pos = snippet.find_uncommented("{")?;
564 // Extract comment between unsafe and block start.
565 let trimmed = &snippet[6..open_pos].trim();
567 if !trimmed.is_empty() {
568 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
569 let budget = shape.width.checked_sub(9)?;
575 Shape::legacy(budget, shape.indent + 7),
583 ast::BlockCheckMode::Default => String::new(),
587 fn rewrite_single_line_block(
588 context: &RewriteContext,
592 ) -> Option<String> {
593 if is_simple_block(block, context.codemap) {
594 let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
595 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
596 let result = format!("{}{{ {} }}", prefix, expr_str);
597 if result.len() <= shape.width && !result.contains('\n') {
604 fn rewrite_block_with_visitor(
605 context: &RewriteContext,
609 ) -> Option<String> {
610 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
614 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
615 visitor.block_indent = shape.indent;
616 visitor.is_if_else_block = context.is_if_else_block;
618 ast::BlockCheckMode::Unsafe(..) => {
619 let snippet = context.snippet(block.span);
620 let open_pos = snippet.find_uncommented("{")?;
621 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
623 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
626 visitor.visit_block(block, None);
627 Some(format!("{}{}", prefix, visitor.buffer))
630 impl Rewrite for ast::Block {
631 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
632 // shape.width is used only for the single line case: either the empty block `{}`,
633 // or an unsafe expression `unsafe { e }`.
634 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
638 let prefix = block_prefix(context, self, shape)?;
640 let result = rewrite_block_with_visitor(context, &prefix, self, shape);
641 if let Some(ref result_str) = result {
642 if result_str.lines().count() <= 3 {
643 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
653 impl Rewrite for ast::Stmt {
654 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
655 skip_out_of_file_lines_range!(context, self.span());
657 let result = match self.node {
658 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
659 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
660 let suffix = if semicolon_for_stmt(context, self) {
666 let shape = shape.sub_width(suffix.len())?;
667 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
669 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
671 result.and_then(|res| recover_comment_removed(res, self.span(), context))
675 // Rewrite condition if the given expression has one.
676 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
678 ast::ExprKind::Match(ref cond, _) => {
680 let cond_shape = match context.config.indent_style() {
681 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
682 IndentStyle::Block => shape.offset_left(8)?,
684 cond.rewrite(context, cond_shape)
686 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
688 String::from("\n") + &shape.indent.block_only().to_string(context.config);
690 .rewrite_cond(context, shape, &alt_block_sep)
691 .and_then(|rw| Some(rw.0))
696 // Abstraction over control flow expressions
698 struct ControlFlow<'a> {
699 cond: Option<&'a ast::Expr>,
700 block: &'a ast::Block,
701 else_block: Option<&'a ast::Expr>,
702 label: Option<ast::SpannedIdent>,
703 pat: Option<&'a ast::Pat>,
707 allow_single_line: bool,
708 // True if this is an `if` expression in an `else if` :-( hacky
713 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
715 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
719 else_block.as_ref().map(|e| &**e),
720 expr_type == ExprType::SubExpression,
724 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
725 Some(ControlFlow::new_if(
729 else_block.as_ref().map(|e| &**e),
730 expr_type == ExprType::SubExpression,
735 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
736 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
738 ast::ExprKind::Loop(ref block, label) => {
739 Some(ControlFlow::new_loop(block, label, expr.span))
741 ast::ExprKind::While(ref cond, ref block, label) => {
742 Some(ControlFlow::new_while(None, cond, block, label, expr.span))
744 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
745 ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
751 impl<'a> ControlFlow<'a> {
754 pat: Option<&'a ast::Pat>,
755 block: &'a ast::Block,
756 else_block: Option<&'a ast::Expr>,
757 allow_single_line: bool,
760 ) -> ControlFlow<'a> {
764 else_block: else_block,
773 allow_single_line: allow_single_line,
774 nested_if: nested_if,
780 block: &'a ast::Block,
781 label: Option<ast::SpannedIdent>,
783 ) -> ControlFlow<'a> {
793 allow_single_line: false,
800 pat: Option<&'a ast::Pat>,
802 block: &'a ast::Block,
803 label: Option<ast::SpannedIdent>,
805 ) -> ControlFlow<'a> {
818 allow_single_line: false,
827 block: &'a ast::Block,
828 label: Option<ast::SpannedIdent>,
830 ) -> ControlFlow<'a> {
840 allow_single_line: false,
846 fn rewrite_single_line(
849 context: &RewriteContext,
851 ) -> Option<String> {
852 assert!(self.allow_single_line);
853 let else_block = self.else_block?;
854 let fixed_cost = self.keyword.len() + " { } else { }".len();
856 if let ast::ExprKind::Block(ref else_node) = else_block.node {
857 if !is_simple_block(self.block, context.codemap)
858 || !is_simple_block(else_node, context.codemap)
859 || pat_expr_str.contains('\n')
864 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
865 let expr = &self.block.stmts[0];
866 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
868 let new_width = new_width.checked_sub(if_str.len())?;
869 let else_expr = &else_node.stmts[0];
870 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
872 if if_str.contains('\n') || else_str.contains('\n') {
876 let result = format!(
877 "{} {} {{ {} }} else {{ {} }}",
884 if result.len() <= width {
893 impl<'a> ControlFlow<'a> {
896 context: &RewriteContext,
899 ) -> Option<(String, usize)> {
900 // Do not take the rhs overhead from the upper expressions into account
901 // when rewriting pattern.
902 let new_width = context
905 .checked_sub(shape.used_width())
907 let fresh_shape = Shape {
911 let constr_shape = if self.nested_if {
912 // We are part of an if-elseif-else chain. Our constraints are tightened.
913 // 7 = "} else " .len()
914 fresh_shape.offset_left(7)?
919 let label_string = rewrite_label(self.label);
920 // 1 = space after keyword.
921 let offset = self.keyword.len() + label_string.len() + 1;
923 let pat_expr_string = match self.cond {
925 let cond_shape = match context.config.indent_style() {
926 IndentStyle::Visual => constr_shape.shrink_left(offset)?,
927 IndentStyle::Block => constr_shape.offset_left(offset)?,
939 None => String::new(),
943 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
949 let one_line_budget = context
952 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
954 let force_newline_brace = context.config.indent_style() == IndentStyle::Block
955 && (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget)
956 && !last_line_extendable(&pat_expr_string);
958 // Try to format if-else on single line.
959 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
960 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
962 if let Some(cond_str) = trial {
963 if cond_str.len() <= context.config.single_line_if_else_max_width() {
964 return Some((cond_str, 0));
969 let cond_span = if let Some(cond) = self.cond {
972 mk_sp(self.block.span.lo(), self.block.span.lo())
975 // `for event in event`
976 // Do not include label in the span.
977 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
978 let between_kwd_cond = mk_sp(
981 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
982 self.pat.map_or(cond_span.lo(), |p| {
983 if self.matcher.is_empty() {
986 context.codemap.span_before(self.span, self.matcher.trim())
991 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
993 let after_cond_comment =
994 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
996 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
998 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
999 || force_newline_brace
1006 let used_width = if pat_expr_string.contains('\n') {
1007 last_line_width(&pat_expr_string)
1009 // 2 = spaces after keyword and condition.
1010 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1018 between_kwd_cond_comment.as_ref().map_or(
1019 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1027 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1034 impl<'a> Rewrite for ControlFlow<'a> {
1035 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1036 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1039 String::from("\n") + &shape.indent.block_only().to_string(context.config);
1040 let (cond_str, used_width) = self.rewrite_cond(context, shape, &alt_block_sep)?;
1041 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1042 if used_width == 0 {
1043 return Some(cond_str);
1046 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1047 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1048 // we should avoid the single line case.
1049 let block_width = if self.else_block.is_some() || self.nested_if {
1054 let block_shape = Shape {
1058 let mut block_context = context.clone();
1059 block_context.is_if_else_block = self.else_block.is_some();
1060 let block_str = rewrite_block_with_visitor(&block_context, "", self.block, block_shape)?;
1062 let mut result = format!("{}{}", cond_str, block_str);
1064 if let Some(else_block) = self.else_block {
1065 let shape = Shape::indented(shape.indent, context.config);
1066 let mut last_in_chain = false;
1067 let rewrite = match else_block.node {
1068 // If the else expression is another if-else expression, prevent it
1069 // from being formatted on a single line.
1070 // Note how we're passing the original shape, as the
1071 // cost of "else" should not cascade.
1072 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1073 ControlFlow::new_if(
1077 next_else_block.as_ref().map(|e| &**e),
1080 mk_sp(else_block.span.lo(), self.span.hi()),
1081 ).rewrite(context, shape)
1083 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1084 ControlFlow::new_if(
1088 next_else_block.as_ref().map(|e| &**e),
1091 mk_sp(else_block.span.lo(), self.span.hi()),
1092 ).rewrite(context, shape)
1095 last_in_chain = true;
1096 // When rewriting a block, the width is only used for single line
1097 // blocks, passing 1 lets us avoid that.
1098 let else_shape = Shape {
1099 width: min(1, shape.width),
1102 format_expr(else_block, ExprType::Statement, context, else_shape)
1106 let between_kwd_else_block = mk_sp(
1107 self.block.span.hi(),
1110 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1112 let between_kwd_else_block_comment =
1113 extract_comment(between_kwd_else_block, context, shape);
1115 let after_else = mk_sp(
1118 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1119 else_block.span.lo(),
1121 let after_else_comment = extract_comment(after_else, context, shape);
1123 let between_sep = match context.config.control_brace_style() {
1124 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1127 ControlBraceStyle::AlwaysSameLine => " ",
1129 let after_sep = match context.config.control_brace_style() {
1130 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1134 result.push_str(&format!(
1136 between_kwd_else_block_comment
1138 .map_or(between_sep, |s| &**s),
1139 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1141 result.push_str(&rewrite?);
1148 fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
1150 Some(ident) => Cow::from(format!("{}: ", ident.node)),
1151 None => Cow::from(""),
1155 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1156 match rewrite_missing_comment(span, shape, context) {
1157 Some(ref comment) if !comment.is_empty() => Some(format!(
1158 "\n{indent}{}\n{indent}",
1160 indent = shape.indent.to_string(context.config)
1166 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1167 let snippet = codemap.span_to_snippet(block.span).unwrap();
1168 contains_comment(&snippet)
1171 // Checks that a block contains no statements, an expression and no comments.
1172 // FIXME: incorrectly returns false when comment is contained completely within
1174 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1175 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1176 && !block_contains_comment(block, codemap))
1179 /// Checks whether a block contains at most one statement or expression, and no comments.
1180 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1181 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1184 /// Checks whether a block contains no statements, expressions, or comments.
1185 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1186 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1189 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1191 ast::StmtKind::Expr(..) => true,
1196 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1197 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1204 // A simple wrapper type against ast::Arm. Used inside write_list().
1205 struct ArmWrapper<'a> {
1206 pub arm: &'a ast::Arm,
1207 // True if the arm is the last one in match expression. Used to decide on whether we should add
1208 // trailing comma to the match arm when `config.trailing_comma() == Never`.
1212 impl<'a> ArmWrapper<'a> {
1213 pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1214 ArmWrapper { arm, is_last }
1218 impl<'a> Rewrite for ArmWrapper<'a> {
1219 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1220 rewrite_match_arm(context, self.arm, shape, self.is_last)
1225 context: &RewriteContext,
1230 attrs: &[ast::Attribute],
1231 ) -> Option<String> {
1232 // Do not take the rhs overhead from the upper expressions into account
1233 // when rewriting match condition.
1234 let cond_shape = Shape {
1235 width: context.budget(shape.used_width()),
1239 let cond_shape = match context.config.indent_style() {
1240 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1241 IndentStyle::Block => cond_shape.offset_left(6)?,
1243 let cond_str = cond.rewrite(context, cond_shape)?;
1244 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1245 let block_sep = match context.config.control_brace_style() {
1246 ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1247 _ if last_line_extendable(&cond_str) => " ",
1249 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1253 let nested_indent_str = shape
1255 .block_indent(context.config)
1256 .to_string(context.config);
1257 // Inner attributes.
1258 let inner_attrs = &inner_attributes(attrs);
1259 let inner_attrs_str = if inner_attrs.is_empty() {
1263 .rewrite(context, shape)
1264 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1267 let open_brace_pos = if inner_attrs.is_empty() {
1268 let hi = if arms.is_empty() {
1273 context.codemap.span_after(mk_sp(cond.span.hi(), hi), "{")
1275 inner_attrs[inner_attrs.len() - 1].span().hi()
1278 let arm_indent_str = if context.config.indent_match_arms() {
1281 shape.indent.to_string(context.config)
1284 if arms.is_empty() {
1285 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1286 if snippet.trim().is_empty() {
1287 Some(format!("match {} {{}}", cond_str))
1289 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1290 Some(context.snippet(span))
1294 "match {}{}{{\n{}{}{}\n{}}}",
1299 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1300 shape.indent.to_string(context.config),
1305 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1306 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1308 } else if config.match_block_trailing_comma() {
1310 } else if let ast::ExprKind::Block(ref block) = body.node {
1311 if let ast::BlockCheckMode::Default = block.rules {
1321 fn rewrite_match_arms(
1322 context: &RewriteContext,
1326 open_brace_pos: BytePos,
1327 ) -> Option<String> {
1328 let arm_shape = if context.config.indent_match_arms() {
1329 shape.block_indent(context.config.tab_spaces())
1331 shape.block_indent(0)
1332 }.with_max_width(context.config);
1334 let arm_len = arms.len();
1335 let is_last_iter = repeat(false)
1336 .take(arm_len.checked_sub(1).unwrap_or(0))
1337 .chain(repeat(true));
1338 let items = itemize_list(
1342 .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1344 |arm| arm.arm.span().lo(),
1345 |arm| arm.arm.span().hi(),
1346 |arm| arm.rewrite(context, arm_shape),
1351 let arms_vec: Vec<_> = items.collect();
1352 let fmt = ListFormatting {
1353 tactic: DefinitiveListTactic::Vertical,
1354 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1356 trailing_separator: SeparatorTactic::Never,
1357 separator_place: SeparatorPlace::Back,
1359 ends_with_newline: true,
1360 preserve_newline: true,
1361 config: context.config,
1364 write_list(&arms_vec, &fmt)
1367 fn rewrite_match_arm(
1368 context: &RewriteContext,
1372 ) -> Option<String> {
1373 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1374 if contains_skip(&arm.attrs) {
1375 let (_, body) = flatten_arm_body(context, &arm.body);
1376 // `arm.span()` does not include trailing comma, add it manually.
1377 return Some(format!(
1379 context.snippet(arm.span()),
1380 arm_comma(context.config, body, is_last),
1383 let missing_span = mk_sp(
1384 arm.attrs[arm.attrs.len() - 1].span.hi(),
1385 arm.pats[0].span.lo(),
1387 (missing_span, arm.attrs.rewrite(context, shape)?)
1389 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1392 rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1393 combine_strs_with_missing_comments(
1407 arm.guard.is_some(),
1412 fn rewrite_match_pattern(
1413 context: &RewriteContext,
1414 pats: &[ptr::P<ast::Pat>],
1415 guard: &Option<ptr::P<ast::Expr>>,
1417 ) -> Option<String> {
1420 let pat_shape = shape.sub_width(5)?;
1422 let pat_strs = pats.iter()
1423 .map(|p| p.rewrite(context, pat_shape))
1424 .collect::<Option<Vec<_>>>()?;
1426 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1427 let tactic = definitive_tactic(
1429 ListTactic::HorizontalVertical,
1430 Separator::VerticalBar,
1433 let fmt = ListFormatting {
1436 trailing_separator: SeparatorTactic::Never,
1437 separator_place: context.config.match_pattern_separator_break_point(),
1439 ends_with_newline: false,
1440 preserve_newline: false,
1441 config: context.config,
1443 let pats_str = write_list(&items, &fmt)?;
1446 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1448 Some(format!("{}{}", pats_str, guard_str))
1452 // @extend: true if the arm body can be put next to `=>`
1453 // @body: flattened body, if the body is block with a single expression
1454 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1456 ast::ExprKind::Block(ref block)
1457 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1459 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1461 !context.config.multiline_match_arm_forces_block()
1462 && expr.can_be_overflowed(context, 1),
1470 !context.config.multiline_match_arm_forces_block()
1471 && body.can_be_overflowed(context, 1),
1477 fn rewrite_match_body(
1478 context: &RewriteContext,
1479 body: &ptr::P<ast::Expr>,
1484 ) -> Option<String> {
1485 let (extend, body) = flatten_arm_body(context, body);
1486 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1487 (true, is_empty_block(block, context.codemap))
1491 let extend = if context.config.match_arm_forces_newline() {
1497 let comma = arm_comma(context.config, body, is_last);
1498 let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1499 let alt_block_sep = alt_block_sep.as_str();
1501 let combine_orig_body = |body_str: &str| {
1502 let block_sep = match context.config.control_brace_style() {
1503 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1507 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1510 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1511 let next_line_indent = if !is_block || is_empty_block {
1512 shape.indent.block_indent(context.config)
1516 let combine_next_line_body = |body_str: &str| {
1518 return Some(format!(
1521 next_line_indent.to_string(context.config),
1526 let indent_str = shape.indent.to_string(context.config);
1527 let nested_indent_str = next_line_indent.to_string(context.config);
1528 let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1529 let comma = if context.config.match_block_trailing_comma() {
1534 ("{", format!("\n{}}}{}", indent_str, comma))
1536 ("", String::from(","))
1539 let block_sep = match context.config.control_brace_style() {
1540 ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1541 _ if body_prefix.is_empty() => "\n".to_owned(),
1542 _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1543 _ => format!(" {}\n", body_prefix),
1544 } + &nested_indent_str;
1555 // Let's try and get the arm body on the same line as the condition.
1557 let orig_body_shape = shape
1558 .offset_left(extra_offset(pats_str, shape) + 4)
1559 .and_then(|shape| shape.sub_width(comma.len()));
1560 let orig_body = if let Some(body_shape) = orig_body_shape {
1561 let rewrite = nop_block_collapse(
1562 format_expr(body, ExprType::Statement, context, body_shape),
1568 if !forbid_same_line && !context.config.match_arm_forces_newline()
1570 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1572 return combine_orig_body(body_str);
1579 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1581 // Try putting body on the next line and see if it looks better.
1582 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1583 let next_line_body = nop_block_collapse(
1584 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1585 next_line_body_shape.width,
1587 match (orig_body, next_line_body) {
1588 (Some(ref orig_str), Some(ref next_line_str))
1589 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1591 combine_next_line_body(next_line_str)
1593 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1594 combine_orig_body(orig_str)
1596 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1597 combine_next_line_body(next_line_str)
1599 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1600 (None, None) => None,
1601 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1605 // The `if ...` guard on a match arm.
1607 context: &RewriteContext,
1608 guard: &Option<ptr::P<ast::Expr>>,
1610 // The amount of space used up on this line for the pattern in
1611 // the arm (excludes offset).
1612 pattern_width: usize,
1613 ) -> Option<String> {
1614 if let Some(ref guard) = *guard {
1615 // First try to fit the guard string on the same line as the pattern.
1616 // 4 = ` if `, 5 = ` => {`
1617 let cond_shape = shape
1618 .offset_left(pattern_width + 4)
1619 .and_then(|s| s.sub_width(5));
1620 if let Some(cond_shape) = cond_shape {
1621 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1622 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1623 return Some(format!(" if {}", cond_str));
1628 // Not enough space to put the guard after the pattern, try a newline.
1629 // 3 = `if `, 5 = ` => {`
1630 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1632 .and_then(|s| s.sub_width(5));
1633 if let Some(cond_shape) = cond_shape {
1634 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1635 return Some(format!(
1637 cond_shape.indent.to_string(context.config),
1649 fn rewrite_pat_expr(
1650 context: &RewriteContext,
1651 pat: Option<&ast::Pat>,
1654 // Connecting piece between pattern and expression,
1655 // *without* trailing space.
1659 ) -> Option<String> {
1660 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1661 if let Some(pat) = pat {
1662 let matcher = if matcher.is_empty() {
1665 format!("{} ", matcher)
1667 let pat_shape = shape
1668 .offset_left(matcher.len())?
1669 .sub_width(connector.len())?;
1670 let pat_string = pat.rewrite(context, pat_shape)?;
1671 let result = format!("{}{}{}", matcher, pat_string, connector);
1672 return rewrite_assign_rhs(context, result, expr, shape);
1675 let expr_rw = expr.rewrite(context, shape);
1676 // The expression may (partially) fit on the current line.
1677 // We do not allow splitting between `if` and condition.
1678 if keyword == "if" || expr_rw.is_some() {
1682 // The expression won't fit on the current line, jump to next.
1683 let nested_shape = shape
1684 .block_indent(context.config.tab_spaces())
1685 .with_max_width(context.config);
1686 let nested_indent_str = nested_shape.indent.to_string(context.config);
1687 expr.rewrite(context, nested_shape)
1688 .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1691 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1693 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1694 _ => wrap_str(context.snippet(l.span), context.config.max_width(), shape),
1698 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1699 let string_lit = context.snippet(span);
1701 if !context.config.format_strings() && !context.config.force_format_strings() {
1706 .all(|line| line.ends_with('\\'))
1708 let new_indent = shape.visual_indent(1).indent;
1709 let indented_string_lit = String::from(
1715 new_indent.to_string(context.config),
1719 .collect::<Vec<_>>()
1723 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1725 return wrap_str(string_lit, context.config.max_width(), shape);
1729 if !context.config.force_format_strings()
1730 && !string_requires_rewrite(context, span, &string_lit, shape)
1732 return wrap_str(string_lit, context.config.max_width(), shape);
1735 // Remove the quote characters.
1736 let str_lit = &string_lit[1..string_lit.len() - 1];
1740 &StringFormat::new(shape.visual_indent(0), context.config),
1745 fn string_requires_rewrite(
1746 context: &RewriteContext,
1751 if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
1755 for (i, line) in string.lines().enumerate() {
1757 if line.len() > shape.width {
1760 } else if line.len() > shape.width + shape.indent.width() {
1768 pub fn rewrite_call(
1769 context: &RewriteContext,
1771 args: &[ptr::P<ast::Expr>],
1774 ) -> Option<String> {
1775 let force_trailing_comma = if context.inside_macro {
1776 span_ends_with_comma(context, span)
1783 &ptr_vec_to_ref_vec(args),
1786 context.config.fn_call_width(),
1787 force_trailing_comma,
1791 pub fn rewrite_call_inner<'a, T>(
1792 context: &RewriteContext,
1797 args_max_width: usize,
1798 force_trailing_comma: bool,
1801 T: Rewrite + Spanned + ToExpr + 'a,
1803 // 2 = `( `, 1 = `(`
1804 let paren_overhead = if context.config.spaces_within_parens_and_brackets() {
1809 let used_width = extra_offset(callee_str, shape);
1810 let one_line_width = shape.width.checked_sub(used_width + 2 * paren_overhead)?;
1812 let nested_shape = shape_from_indent_style(
1815 used_width + 2 * paren_overhead,
1816 used_width + paren_overhead,
1819 let span_lo = context.codemap.span_after(span, "(");
1820 let args_span = mk_sp(span_lo, span.hi());
1822 let (extendable, list_str) = rewrite_call_args(
1829 force_trailing_comma,
1832 if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
1833 let mut new_context = context.clone();
1834 new_context.use_block = true;
1835 return rewrite_call_inner(
1842 force_trailing_comma,
1846 let args_shape = shape.sub_width(last_line_width(callee_str))?;
1850 wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
1854 fn need_block_indent(s: &str, shape: Shape) -> bool {
1855 s.lines().skip(1).any(|s| {
1856 s.find(|c| !char::is_whitespace(c))
1857 .map_or(false, |w| w + 1 < shape.indent.width())
1861 fn rewrite_call_args<'a, T>(
1862 context: &RewriteContext,
1866 one_line_width: usize,
1867 args_max_width: usize,
1868 force_trailing_comma: bool,
1869 ) -> Option<(bool, String)>
1871 T: Rewrite + Spanned + ToExpr + 'a,
1873 let items = itemize_list(
1877 |item| item.span().lo(),
1878 |item| item.span().hi(),
1879 |item| item.rewrite(context, shape),
1884 let mut item_vec: Vec<_> = items.collect();
1886 // Try letting the last argument overflow to the next line with block
1887 // indentation. If its first line fits on one line with the other arguments,
1888 // we format the function arguments horizontally.
1889 let tactic = try_overflow_last_arg(
1898 let fmt = ListFormatting {
1901 trailing_separator: if force_trailing_comma {
1902 SeparatorTactic::Always
1903 } else if context.inside_macro || !context.use_block_indent() {
1904 SeparatorTactic::Never
1906 context.config.trailing_comma()
1908 separator_place: SeparatorPlace::Back,
1910 ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
1911 preserve_newline: false,
1912 config: context.config,
1915 write_list(&item_vec, &fmt).map(|args_str| {
1916 (tactic != DefinitiveListTactic::Vertical, args_str)
1920 fn try_overflow_last_arg<'a, T>(
1921 context: &RewriteContext,
1922 item_vec: &mut Vec<ListItem>,
1925 one_line_width: usize,
1926 args_max_width: usize,
1927 ) -> DefinitiveListTactic
1929 T: Rewrite + Spanned + ToExpr + 'a,
1931 let overflow_last = can_be_overflowed(context, args);
1933 // Replace the last item with its first line to see if it fits with
1935 let placeholder = if overflow_last {
1936 let mut context = context.clone();
1937 if let Some(expr) = args[args.len() - 1].to_expr() {
1938 if let ast::ExprKind::MethodCall(..) = expr.node {
1939 context.force_one_line_chain = true;
1942 last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
1943 rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
1949 let mut tactic = definitive_tactic(
1951 ListTactic::LimitedHorizontalVertical(args_max_width),
1956 // Replace the stub with the full overflowing last argument if the rewrite
1957 // succeeded and its first line fits with the other arguments.
1958 match (overflow_last, tactic, placeholder) {
1959 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1960 item_vec[args.len() - 1].item = placeholder;
1962 _ if args.len() >= 1 => {
1963 item_vec[args.len() - 1].item = args.last()
1964 .and_then(|last_arg| last_arg.rewrite(context, shape));
1965 // Use horizontal layout for a function with a single argument as long as
1966 // everything fits in a single line.
1968 && args_max_width != 0 // Vertical layout is forced.
1969 && !item_vec[0].has_comment()
1970 && !item_vec[0].inner_as_ref().contains('\n')
1971 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
1973 tactic = DefinitiveListTactic::Horizontal;
1975 tactic = definitive_tactic(
1977 ListTactic::LimitedHorizontalVertical(args_max_width),
1990 context: &RewriteContext,
1993 args_max_width: usize,
1994 ) -> Option<Shape> {
1995 let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
1996 acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
1998 let max_width = min(args_max_width, shape.width);
1999 let arg_indent = if context.use_block_indent() {
2000 shape.block().indent.block_unindent(context.config)
2002 shape.block().indent
2005 width: max_width.checked_sub(overhead)?,
2011 fn rewrite_last_arg_with_overflow<'a, T>(
2012 context: &RewriteContext,
2014 last_item: &mut ListItem,
2018 T: Rewrite + Spanned + ToExpr + 'a,
2020 let last_arg = args[args.len() - 1];
2021 let rewrite = if let Some(expr) = last_arg.to_expr() {
2023 // When overflowing the closure which consists of a single control flow expression,
2024 // force to use block if its condition uses multi line.
2025 ast::ExprKind::Closure(..) => {
2026 // If the argument consists of multiple closures, we do not overflow
2027 // the last closure.
2028 if closures::args_have_many_closure(args) {
2031 closures::rewrite_last_closure(context, expr, shape)
2034 _ => expr.rewrite(context, shape),
2037 last_arg.rewrite(context, shape)
2040 if let Some(rewrite) = rewrite {
2041 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2042 last_item.item = rewrite_first_line;
2049 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2051 T: Rewrite + Spanned + ToExpr + 'a,
2054 .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2057 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2059 ast::ExprKind::Match(..) => {
2060 (context.use_block_indent() && args_len == 1)
2061 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
2063 ast::ExprKind::If(..) |
2064 ast::ExprKind::IfLet(..) |
2065 ast::ExprKind::ForLoop(..) |
2066 ast::ExprKind::Loop(..) |
2067 ast::ExprKind::While(..) |
2068 ast::ExprKind::WhileLet(..) => {
2069 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2071 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2072 context.use_block_indent()
2073 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
2075 ast::ExprKind::Array(..) |
2076 ast::ExprKind::Call(..) |
2077 ast::ExprKind::Mac(..) |
2078 ast::ExprKind::MethodCall(..) |
2079 ast::ExprKind::Struct(..) |
2080 ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2081 ast::ExprKind::AddrOf(_, ref expr) |
2082 ast::ExprKind::Box(ref expr) |
2083 ast::ExprKind::Try(ref expr) |
2084 ast::ExprKind::Unary(_, ref expr) |
2085 ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2090 pub fn wrap_args_with_parens(
2091 context: &RewriteContext,
2093 is_extendable: bool,
2095 nested_shape: Shape,
2097 if !context.use_block_indent()
2098 || (context.inside_macro && !args_str.contains('\n')
2099 && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2101 if context.config.spaces_within_parens_and_brackets() && !args_str.is_empty() {
2102 format!("( {} )", args_str)
2104 format!("({})", args_str)
2109 nested_shape.indent.to_string(context.config),
2111 shape.block().indent.to_string(context.config)
2116 /// Return true if a function call or a method call represented by the given span ends with a
2117 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2118 /// comma from macro can potentially break the code.
2119 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2120 let mut encountered_closing_paren = false;
2121 for c in context.snippet(span).chars().rev() {
2124 ')' => if encountered_closing_paren {
2127 encountered_closing_paren = true;
2129 _ if c.is_whitespace() => continue,
2136 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2137 debug!("rewrite_paren, shape: {:?}", shape);
2138 let total_paren_overhead = paren_overhead(context);
2139 let paren_overhead = total_paren_overhead / 2;
2140 let sub_shape = shape
2141 .offset_left(paren_overhead)
2142 .and_then(|s| s.sub_width(paren_overhead))?;
2145 |s: &str| if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2146 format!("( {} )", s)
2151 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2152 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2154 if subexpr_str.contains('\n')
2155 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2157 Some(paren_wrapper(&subexpr_str))
2166 context: &RewriteContext,
2168 ) -> Option<String> {
2169 let expr_str = expr.rewrite(context, shape)?;
2171 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2177 let offset = last_line_width(&expr_str) + lbr.len();
2178 let rhs_overhead = shape.rhs_overhead(context.config);
2179 let index_shape = if expr_str.contains('\n') {
2180 Shape::legacy(context.config.max_width(), shape.indent)
2181 .offset_left(offset)
2182 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2184 shape.visual_indent(offset).sub_width(offset + rbr.len())
2186 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2188 // Return if index fits in a single line.
2189 match orig_index_rw {
2190 Some(ref index_str) if !index_str.contains('\n') => {
2191 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2196 // Try putting index on the next line and see if it fits in a single line.
2197 let indent = shape.indent.block_indent(context.config);
2198 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2199 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2200 let new_index_rw = index.rewrite(context, index_shape);
2201 match (orig_index_rw, new_index_rw) {
2202 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2205 indent.to_string(context.config),
2210 (None, Some(ref new_index_str)) => Some(format!(
2213 indent.to_string(context.config),
2218 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2223 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2228 fields.iter().all(|field| !field.is_shorthand)
2231 fn rewrite_struct_lit<'a>(
2232 context: &RewriteContext,
2234 fields: &'a [ast::Field],
2235 base: Option<&'a ast::Expr>,
2238 ) -> Option<String> {
2239 debug!("rewrite_struct_lit: shape {:?}", shape);
2241 enum StructLitField<'a> {
2242 Regular(&'a ast::Field),
2243 Base(&'a ast::Expr),
2247 let path_shape = shape.sub_width(2)?;
2248 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2250 if fields.is_empty() && base.is_none() {
2251 return Some(format!("{} {{}}", path_str));
2254 // Foo { a: Foo } - indent is +3, width is -5.
2255 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2257 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2258 let body_lo = context.codemap.span_after(span, "{");
2259 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2260 && context.config.struct_field_align_threshold() > 0
2262 rewrite_with_alignment(
2266 mk_sp(body_lo, span.hi()),
2270 let field_iter = fields
2272 .map(StructLitField::Regular)
2273 .chain(base.into_iter().map(StructLitField::Base));
2275 let span_lo = |item: &StructLitField| match *item {
2276 StructLitField::Regular(field) => field.span().lo(),
2277 StructLitField::Base(expr) => {
2278 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2279 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2280 let pos = snippet.find_uncommented("..").unwrap();
2281 last_field_hi + BytePos(pos as u32)
2284 let span_hi = |item: &StructLitField| match *item {
2285 StructLitField::Regular(field) => field.span().hi(),
2286 StructLitField::Base(expr) => expr.span.hi(),
2288 let rewrite = |item: &StructLitField| match *item {
2289 StructLitField::Regular(field) => {
2290 // The 1 taken from the v_budget is for the comma.
2291 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2293 StructLitField::Base(expr) => {
2295 expr.rewrite(context, v_shape.offset_left(2)?)
2296 .map(|s| format!("..{}", s))
2300 let items = itemize_list(
2311 let item_vec = items.collect::<Vec<_>>();
2313 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2314 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2315 let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2317 write_list(&item_vec, &fmt)?
2320 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2321 Some(format!("{} {{{}}}", path_str, fields_str))
2323 // FIXME if context.config.indent_style() == Visual, but we run out
2324 // of space, we should fall back to BlockIndent.
2327 pub fn wrap_struct_field(
2328 context: &RewriteContext,
2331 nested_shape: Shape,
2332 one_line_width: usize,
2334 if context.config.indent_style() == IndentStyle::Block
2335 && (fields_str.contains('\n')
2336 || context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti
2337 || fields_str.len() > one_line_width)
2341 nested_shape.indent.to_string(context.config),
2343 shape.indent.to_string(context.config)
2346 // One liner or visual indent.
2347 format!(" {} ", fields_str)
2351 pub fn struct_lit_field_separator(config: &Config) -> &str {
2352 colon_spaces(config.space_before_colon(), config.space_after_colon())
2355 pub fn rewrite_field(
2356 context: &RewriteContext,
2359 prefix_max_width: usize,
2360 ) -> Option<String> {
2361 if contains_skip(&field.attrs) {
2362 return Some(context.snippet(field.span()));
2364 let name = &field.ident.node.to_string();
2365 if field.is_shorthand {
2366 Some(name.to_string())
2368 let mut separator = String::from(struct_lit_field_separator(context.config));
2369 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2370 separator.push(' ');
2372 let overhead = name.len() + separator.len();
2373 let expr_shape = shape.offset_left(overhead)?;
2374 let expr = field.expr.rewrite(context, expr_shape);
2376 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2377 if !attrs_str.is_empty() {
2378 attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2382 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2384 let expr_offset = shape.indent.block_indent(context.config);
2387 .rewrite(context, Shape::indented(expr_offset, context.config));
2393 expr_offset.to_string(context.config),
2402 fn shape_from_indent_style(
2403 context: &RewriteContext,
2407 ) -> Option<Shape> {
2408 if context.use_block_indent() {
2412 .block_indent(context.config.tab_spaces())
2413 .with_max_width(context.config)
2416 shape.visual_indent(offset).sub_width(overhead)
2420 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2421 context: &RewriteContext,
2427 T: Rewrite + Spanned + ToExpr + 'a,
2429 let mut items = items.iter();
2430 // In case of length 1, need a trailing comma
2431 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2432 if items.len() == 1 {
2434 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2438 .rewrite(context, nested_shape)
2440 if context.config.spaces_within_parens_and_brackets() {
2441 format!("( {}, )", s)
2448 let list_lo = context.codemap.span_after(span, "(");
2449 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2450 let items = itemize_list(
2454 |item| item.span().lo(),
2455 |item| item.span().hi(),
2456 |item| item.rewrite(context, nested_shape),
2458 span.hi() - BytePos(1),
2461 let item_vec: Vec<_> = items.collect();
2462 let tactic = definitive_tactic(
2464 ListTactic::HorizontalVertical,
2468 let fmt = ListFormatting {
2471 trailing_separator: SeparatorTactic::Never,
2472 separator_place: SeparatorPlace::Back,
2474 ends_with_newline: false,
2475 preserve_newline: false,
2476 config: context.config,
2478 let list_str = write_list(&item_vec, &fmt)?;
2480 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2481 Some(format!("( {} )", list_str))
2483 Some(format!("({})", list_str))
2487 pub fn rewrite_tuple<'a, T>(
2488 context: &RewriteContext,
2494 T: Rewrite + Spanned + ToExpr + 'a,
2496 debug!("rewrite_tuple {:?}", shape);
2497 if context.use_block_indent() {
2498 // We use the same rule as function calls for rewriting tuples.
2499 let force_trailing_comma = if context.inside_macro {
2500 span_ends_with_comma(context, span)
2510 context.config.fn_call_width(),
2511 force_trailing_comma,
2514 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2518 pub fn rewrite_unary_prefix<R: Rewrite>(
2519 context: &RewriteContext,
2523 ) -> Option<String> {
2525 .rewrite(context, shape.offset_left(prefix.len())?)
2526 .map(|r| format!("{}{}", prefix, r))
2529 // FIXME: this is probably not correct for multi-line Rewrites. we should
2530 // subtract suffix.len() from the last line budget, not the first!
2531 pub fn rewrite_unary_suffix<R: Rewrite>(
2532 context: &RewriteContext,
2536 ) -> Option<String> {
2538 .rewrite(context, shape.sub_width(suffix.len())?)
2545 fn rewrite_unary_op(
2546 context: &RewriteContext,
2550 ) -> Option<String> {
2551 // For some reason, an UnOp is not spanned like BinOp!
2552 let operator_str = match *op {
2553 ast::UnOp::Deref => "*",
2554 ast::UnOp::Not => "!",
2555 ast::UnOp::Neg => "-",
2557 rewrite_unary_prefix(context, operator_str, expr, shape)
2560 fn rewrite_assignment(
2561 context: &RewriteContext,
2564 op: Option<&ast::BinOp>,
2566 ) -> Option<String> {
2567 let operator_str = match op {
2568 Some(op) => context.snippet(op.span),
2569 None => "=".to_owned(),
2572 // 1 = space between lhs and operator.
2573 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2574 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2576 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2579 // The left hand side must contain everything up to, and including, the
2580 // assignment operator.
2581 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2582 context: &RewriteContext,
2586 ) -> Option<String> {
2587 let lhs = lhs.into();
2588 let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2589 shape.indent.width()
2593 // 1 = space between operator and rhs.
2594 let orig_shape = shape.offset_left(last_line_width + 1)?;
2595 let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2599 pub fn choose_rhs<R: Rewrite>(
2600 context: &RewriteContext,
2603 orig_rhs: Option<String>,
2604 ) -> Option<String> {
2606 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2607 Some(format!(" {}", new_str))
2610 // Expression did not fit on the same line as the identifier.
2611 // Try splitting the line and see if that works better.
2612 let new_shape = Shape::indented(
2613 shape.block().indent.block_indent(context.config),
2615 ).sub_width(shape.rhs_overhead(context.config))?;
2616 let new_rhs = expr.rewrite(context, new_shape);
2617 let new_indent_str = &new_shape.indent.to_string(context.config);
2619 match (orig_rhs, new_rhs) {
2620 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2621 Some(format!("\n{}{}", new_indent_str, new_rhs))
2623 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2624 (None, None) => None,
2625 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2631 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2632 fn count_line_breaks(src: &str) -> usize {
2633 src.chars().filter(|&x| x == '\n').count()
2636 !next_line_rhs.contains('\n')
2637 || count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2640 fn rewrite_expr_addrof(
2641 context: &RewriteContext,
2642 mutability: ast::Mutability,
2645 ) -> Option<String> {
2646 let operator_str = match mutability {
2647 ast::Mutability::Immutable => "&",
2648 ast::Mutability::Mutable => "&mut ",
2650 rewrite_unary_prefix(context, operator_str, expr, shape)
2654 fn to_expr(&self) -> Option<&ast::Expr>;
2655 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2658 impl ToExpr for ast::Expr {
2659 fn to_expr(&self) -> Option<&ast::Expr> {
2663 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2664 can_be_overflowed_expr(context, self, len)
2668 impl ToExpr for ast::Ty {
2669 fn to_expr(&self) -> Option<&ast::Expr> {
2673 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2674 can_be_overflowed_type(context, self, len)
2678 impl<'a> ToExpr for TuplePatField<'a> {
2679 fn to_expr(&self) -> Option<&ast::Expr> {
2683 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2684 can_be_overflowed_pat(context, self, len)
2688 impl<'a> ToExpr for ast::StructField {
2689 fn to_expr(&self) -> Option<&ast::Expr> {
2693 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2698 impl<'a> ToExpr for MacroArg {
2699 fn to_expr(&self) -> Option<&ast::Expr> {
2701 MacroArg::Expr(ref expr) => Some(expr),
2706 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2708 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2709 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2710 MacroArg::Pat(..) => false,