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.
15 use syntax::codemap::{BytePos, CodeMap, Span};
16 use syntax::parse::token::DelimToken;
17 use syntax::{ast, ptr};
19 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
23 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
24 rewrite_missing_comment, CharClasses, FindUncommented,
26 use config::{Config, ControlBraceStyle, IndentStyle};
28 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
29 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
31 use macros::{rewrite_macro, MacroArg, MacroPosition};
32 use matches::rewrite_match;
34 use patterns::{can_be_overflowed_pat, is_short_pattern, TuplePatField};
35 use rewrite::{Rewrite, RewriteContext};
36 use shape::{Indent, Shape};
38 use string::{rewrite_string, StringFormat};
39 use types::{can_be_overflowed_type, rewrite_path, PathContext};
41 colon_spaces, contains_skip, count_newlines, first_line_width, inner_attributes,
42 last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
43 semicolon_for_stmt, wrap_str,
45 use vertical::rewrite_with_alignment;
46 use visitor::FmtVisitor;
48 impl Rewrite for ast::Expr {
49 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
50 format_expr(self, ExprType::SubExpression, context, shape)
54 #[derive(Copy, Clone, PartialEq)]
63 context: &RewriteContext,
66 skip_out_of_file_lines_range!(context, expr.span);
68 if contains_skip(&*expr.attrs) {
69 return Some(context.snippet(expr.span()).to_owned());
72 let expr_rw = match expr.node {
73 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
75 &ptr_vec_to_ref_vec(expr_vec),
79 choose_separator_tactic(context, expr.span),
82 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
83 ast::ExprKind::Call(ref callee, ref args) => {
84 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
85 let callee_str = callee.rewrite(context, shape)?;
86 rewrite_call(context, &callee_str, args, inner_span, shape)
88 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
89 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
90 // FIXME: format comments between operands and operator
91 rewrite_simple_binaries(context, expr, shape, op).or_else(|| {
95 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
98 context.config.binop_separator(),
102 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
103 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
107 base.as_ref().map(|e| &**e),
111 ast::ExprKind::Tup(ref items) => {
112 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
114 ast::ExprKind::If(..)
115 | ast::ExprKind::IfLet(..)
116 | ast::ExprKind::ForLoop(..)
117 | ast::ExprKind::Loop(..)
118 | ast::ExprKind::While(..)
119 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
120 .and_then(|control_flow| control_flow.rewrite(context, shape)),
121 ast::ExprKind::Block(ref block) => {
123 ExprType::Statement => {
124 if is_unsafe_block(block) {
125 rewrite_block(block, Some(&expr.attrs), context, shape)
126 } else if let rw @ Some(_) =
127 rewrite_empty_block(context, block, Some(&expr.attrs), "", shape)
129 // Rewrite block without trying to put it in a single line.
132 let prefix = block_prefix(context, block, shape)?;
133 rewrite_block_with_visitor(
143 ExprType::SubExpression => rewrite_block(block, Some(&expr.attrs), context, shape),
146 ast::ExprKind::Match(ref cond, ref arms) => {
147 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
149 ast::ExprKind::Path(ref qself, ref path) => {
150 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
152 ast::ExprKind::Assign(ref lhs, ref rhs) => {
153 rewrite_assignment(context, lhs, rhs, None, shape)
155 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
156 rewrite_assignment(context, lhs, rhs, Some(op), shape)
158 ast::ExprKind::Continue(ref opt_label) => {
159 let id_str = match *opt_label {
160 Some(label) => format!(" {}", label.ident),
161 None => String::new(),
163 Some(format!("continue{}", id_str))
165 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
166 let id_str = match *opt_label {
167 Some(label) => format!(" {}", label.ident),
168 None => String::new(),
171 if let Some(ref expr) = *opt_expr {
172 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
174 Some(format!("break{}", id_str))
177 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
178 rewrite_unary_prefix(context, "yield ", &**expr, shape)
180 Some("yield".to_string())
182 ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
183 closures::rewrite_closure(
184 capture, movability, fn_decl, body, expr.span, context, shape,
187 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
188 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) => rewrite_pair(
229 PairParts::new("[", "; ", "]"),
232 SeparatorPlace::Back,
234 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
235 let delim = match limits {
236 ast::RangeLimits::HalfOpen => "..",
237 ast::RangeLimits::Closed => "..=",
240 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
242 ast::ExprKind::Lit(ref lit) => match lit.node {
243 ast::LitKind::FloatUnsuffixed(..) => {
244 context.snippet(lit.span).ends_with('.')
252 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
254 // Don't format `.. ..` into `....`, which is invalid.
256 // This check is unnecessary for `lhs`, because a range
257 // starting from another range needs parentheses as `(x ..) ..`
258 // (`x .. ..` is a range from `x` to `..`).
259 ast::ExprKind::Range(None, _, _) => true,
264 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
265 let space_if = |b: bool| if b { " " } else { "" };
269 lhs.map(|lhs| space_if(needs_space_before_range(context, lhs)))
272 rhs.map(|rhs| space_if(needs_space_after_range(rhs)))
277 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
278 (Some(lhs), Some(rhs)) => {
279 let sp_delim = if context.config.spaces_around_ranges() {
280 format!(" {} ", delim)
282 default_sp_delim(Some(lhs), Some(rhs))
287 PairParts::new("", &sp_delim, ""),
290 context.config.binop_separator(),
293 (None, Some(rhs)) => {
294 let sp_delim = if context.config.spaces_around_ranges() {
295 format!("{} ", delim)
297 default_sp_delim(None, Some(rhs))
299 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
301 (Some(lhs), None) => {
302 let sp_delim = if context.config.spaces_around_ranges() {
303 format!(" {}", delim)
305 default_sp_delim(Some(lhs), None)
307 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
309 (None, None) => Some(delim.to_owned()),
312 // We do not format these expressions yet, but they should still
313 // satisfy our width restrictions.
314 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
315 ast::ExprKind::Catch(ref block) => {
316 if let rw @ Some(_) =
317 rewrite_single_line_block(context, "do catch ", block, Some(&expr.attrs), shape)
322 let budget = shape.width.saturating_sub(9);
330 Shape::legacy(budget, shape.indent)
338 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
339 .and_then(|expr_str| {
340 let attrs = outer_attributes(&expr.attrs);
341 let attrs_str = attrs.rewrite(context, shape)?;
343 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
346 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
350 /// Collect operands that appears in the given binary operator in the opposite order.
351 /// e.g. `collect_binary_items(e, ||)` for `a && b || c || d` returns `[d, c, a && b]`.
352 fn collect_binary_items<'a>(mut expr: &'a ast::Expr, binop: ast::BinOp) -> Vec<&'a ast::Expr> {
353 let mut result = vec![];
354 let mut prev_lhs = None;
357 ast::ExprKind::Binary(inner_binop, ref lhs, ref rhs)
358 if inner_binop.node == binop.node =>
362 prev_lhs = Some(lhs);
365 if let Some(lhs) = prev_lhs {
375 /// Rewrites a binary expression whose operands fits within a single line.
376 fn rewrite_simple_binaries(
377 context: &RewriteContext,
381 ) -> Option<String> {
382 let op_str = context.snippet(op.span);
384 // 2 = spaces around a binary operator.
385 let sep_overhead = op_str.len() + 2;
386 let nested_overhead = sep_overhead - 1;
388 let nested_shape = (match context.config.indent_style() {
389 IndentStyle::Visual => shape.visual_indent(0),
390 IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
391 }).with_max_width(context.config);
392 let nested_shape = match context.config.binop_separator() {
393 SeparatorPlace::Back => nested_shape.sub_width(nested_overhead)?,
394 SeparatorPlace::Front => nested_shape.offset_left(nested_overhead)?,
397 let opt_rewrites: Option<Vec<_>> = collect_binary_items(expr, op)
400 .map(|e| e.rewrite(context, nested_shape))
402 if let Some(rewrites) = opt_rewrites {
403 if rewrites.iter().all(|e| ::utils::is_single_line(e)) {
404 let total_width = rewrites.iter().map(|s| s.len()).sum::<usize>()
405 + sep_overhead * (rewrites.len() - 1);
407 let sep_str = if total_width <= shape.width {
408 format!(" {} ", op_str)
410 let indent_str = nested_shape.indent.to_string_with_newline(context.config);
411 match context.config.binop_separator() {
412 SeparatorPlace::Back => format!(" {}{}", op_str.trim_right(), indent_str),
413 SeparatorPlace::Front => format!("{}{} ", indent_str, op_str.trim_left()),
417 return wrap_str(rewrites.join(&sep_str), context.config.max_width(), shape);
424 #[derive(new, Clone, Copy)]
425 pub struct PairParts<'a> {
431 pub fn rewrite_pair<LHS, RHS>(
435 context: &RewriteContext,
437 separator_place: SeparatorPlace,
443 let lhs_overhead = match separator_place {
444 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
445 SeparatorPlace::Front => shape.used_width(),
447 let lhs_shape = Shape {
448 width: context.budget(lhs_overhead),
452 .rewrite(context, lhs_shape)
453 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
455 // Try to put both lhs and rhs on the same line.
456 let rhs_orig_result = shape
457 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
458 .and_then(|s| s.sub_width(pp.suffix.len()))
459 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
460 if let Some(ref rhs_result) = rhs_orig_result {
461 // If the length of the lhs is equal to or shorter than the tab width or
462 // the rhs looks like block expression, we put the rhs on the same
463 // line with the lhs even if the rhs is multi-lined.
464 let allow_same_line = lhs_result.len() <= context.config.tab_spaces()
468 .map(|first_line| first_line.ends_with('{'))
470 if !rhs_result.contains('\n') || allow_same_line {
471 let one_line_width = last_line_width(&lhs_result)
473 + first_line_width(rhs_result)
475 if one_line_width <= shape.width {
478 lhs_result, pp.infix, rhs_result, pp.suffix
484 // We have to use multiple lines.
485 // Re-evaluate the rhs because we have more space now:
486 let mut rhs_shape = match context.config.indent_style() {
487 IndentStyle::Visual => shape
488 .sub_width(pp.suffix.len() + pp.prefix.len())?
489 .visual_indent(pp.prefix.len()),
490 IndentStyle::Block => {
491 // Try to calculate the initial constraint on the right hand side.
492 let rhs_overhead = shape.rhs_overhead(context.config);
493 Shape::indented(shape.indent.block_indent(context.config), context.config)
494 .sub_width(rhs_overhead)?
497 let infix = match separator_place {
498 SeparatorPlace::Back => pp.infix.trim_right(),
499 SeparatorPlace::Front => pp.infix.trim_left(),
501 if separator_place == SeparatorPlace::Front {
502 rhs_shape = rhs_shape.offset_left(infix.len())?;
504 let rhs_result = rhs.rewrite(context, rhs_shape)?;
505 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
506 let infix_with_sep = match separator_place {
507 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
508 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
512 lhs_result, infix_with_sep, rhs_result, pp.suffix
516 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
520 context: &RewriteContext,
522 force_separator_tactic: Option<SeparatorTactic>,
523 delim_token: Option<DelimToken>,
524 ) -> Option<String> {
525 overflow::rewrite_with_square_brackets(
531 force_separator_tactic,
536 fn rewrite_empty_block(
537 context: &RewriteContext,
539 attrs: Option<&[ast::Attribute]>,
542 ) -> Option<String> {
543 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
547 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
549 return Some(format!("{}{{}}", prefix));
552 // If a block contains only a single-line comment, then leave it on one line.
553 let user_str = context.snippet(block.span);
554 let user_str = user_str.trim();
555 if user_str.starts_with('{') && user_str.ends_with('}') {
556 let comment_str = user_str[1..user_str.len() - 1].trim();
557 if block.stmts.is_empty()
558 && !comment_str.contains('\n')
559 && !comment_str.starts_with("//")
560 && comment_str.len() + 4 <= shape.width
562 return Some(format!("{}{{ {} }}", prefix, comment_str));
569 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
570 Some(match block.rules {
571 ast::BlockCheckMode::Unsafe(..) => {
572 let snippet = context.snippet(block.span);
573 let open_pos = snippet.find_uncommented("{")?;
574 // Extract comment between unsafe and block start.
575 let trimmed = &snippet[6..open_pos].trim();
577 if !trimmed.is_empty() {
578 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
579 let budget = shape.width.checked_sub(9)?;
585 Shape::legacy(budget, shape.indent + 7),
593 ast::BlockCheckMode::Default => String::new(),
597 fn rewrite_single_line_block(
598 context: &RewriteContext,
601 attrs: Option<&[ast::Attribute]>,
603 ) -> Option<String> {
604 if is_simple_block(block, attrs, context.codemap) {
605 let expr_shape = shape.offset_left(last_line_width(prefix))?;
606 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
607 let result = format!("{}{{ {} }}", prefix, expr_str);
608 if result.len() <= shape.width && !result.contains('\n') {
615 pub fn rewrite_block_with_visitor(
616 context: &RewriteContext,
619 attrs: Option<&[ast::Attribute]>,
622 ) -> Option<String> {
623 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, prefix, shape) {
627 let mut visitor = FmtVisitor::from_context(context);
628 visitor.block_indent = shape.indent;
629 visitor.is_if_else_block = context.is_if_else_block();
631 ast::BlockCheckMode::Unsafe(..) => {
632 let snippet = context.snippet(block.span);
633 let open_pos = snippet.find_uncommented("{")?;
634 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
636 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
639 let inner_attrs = attrs.map(inner_attributes);
640 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
641 Some(format!("{}{}", prefix, visitor.buffer))
644 impl Rewrite for ast::Block {
645 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
646 rewrite_block(self, None, context, shape)
652 attrs: Option<&[ast::Attribute]>,
653 context: &RewriteContext,
655 ) -> Option<String> {
656 let prefix = block_prefix(context, block, shape)?;
658 // shape.width is used only for the single line case: either the empty block `{}`,
659 // or an unsafe expression `unsafe { e }`.
660 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, &prefix, shape) {
664 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, shape, true);
665 if let Some(ref result_str) = result {
666 if result_str.lines().count() <= 3 {
667 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, block, attrs, shape) {
676 impl Rewrite for ast::Stmt {
677 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
678 skip_out_of_file_lines_range!(context, self.span());
680 let result = match self.node {
681 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
682 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
683 let suffix = if semicolon_for_stmt(context, self) {
689 let shape = shape.sub_width(suffix.len())?;
690 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
692 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
694 result.and_then(|res| recover_comment_removed(res, self.span(), context))
698 // Rewrite condition if the given expression has one.
699 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
701 ast::ExprKind::Match(ref cond, _) => {
703 let cond_shape = match context.config.indent_style() {
704 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
705 IndentStyle::Block => shape.offset_left(8)?,
707 cond.rewrite(context, cond_shape)
709 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
711 String::from("\n") + &shape.indent.block_only().to_string(context.config);
713 .rewrite_cond(context, shape, &alt_block_sep)
714 .and_then(|rw| Some(rw.0))
719 // Abstraction over control flow expressions
721 struct ControlFlow<'a> {
722 cond: Option<&'a ast::Expr>,
723 block: &'a ast::Block,
724 else_block: Option<&'a ast::Expr>,
725 label: Option<ast::Label>,
726 pats: Vec<&'a ast::Pat>,
730 allow_single_line: bool,
731 // True if this is an `if` expression in an `else if` :-( hacky
736 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
738 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
742 else_block.as_ref().map(|e| &**e),
743 expr_type == ExprType::SubExpression,
747 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
748 Some(ControlFlow::new_if(
750 ptr_vec_to_ref_vec(pat),
752 else_block.as_ref().map(|e| &**e),
753 expr_type == ExprType::SubExpression,
758 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
759 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
761 ast::ExprKind::Loop(ref block, label) => {
762 Some(ControlFlow::new_loop(block, label, expr.span))
764 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
771 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
772 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
778 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
786 impl<'a> ControlFlow<'a> {
789 pats: Vec<&'a ast::Pat>,
790 block: &'a ast::Block,
791 else_block: Option<&'a ast::Expr>,
792 allow_single_line: bool,
795 ) -> ControlFlow<'a> {
796 let matcher = choose_matcher(&pats);
812 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
822 allow_single_line: false,
829 pats: Vec<&'a ast::Pat>,
831 block: &'a ast::Block,
832 label: Option<ast::Label>,
834 ) -> ControlFlow<'a> {
835 let matcher = choose_matcher(&pats);
845 allow_single_line: false,
854 block: &'a ast::Block,
855 label: Option<ast::Label>,
857 ) -> ControlFlow<'a> {
867 allow_single_line: false,
873 fn rewrite_single_line(
876 context: &RewriteContext,
878 ) -> Option<String> {
879 assert!(self.allow_single_line);
880 let else_block = self.else_block?;
881 let fixed_cost = self.keyword.len() + " { } else { }".len();
883 if let ast::ExprKind::Block(ref else_node) = else_block.node {
884 if !is_simple_block(self.block, None, context.codemap)
885 || !is_simple_block(else_node, None, context.codemap)
886 || pat_expr_str.contains('\n')
891 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
892 let expr = &self.block.stmts[0];
893 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
895 let new_width = new_width.checked_sub(if_str.len())?;
896 let else_expr = &else_node.stmts[0];
897 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
899 if if_str.contains('\n') || else_str.contains('\n') {
903 let result = format!(
904 "{} {} {{ {} }} else {{ {} }}",
905 self.keyword, pat_expr_str, if_str, else_str
908 if result.len() <= width {
917 impl<'a> ControlFlow<'a> {
920 context: &RewriteContext,
924 ) -> Option<String> {
925 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
927 let cond_shape = shape.offset_left(offset)?;
928 if !self.pats.is_empty() {
929 let matcher = if self.matcher.is_empty() {
930 self.matcher.to_owned()
932 format!("{} ", self.matcher)
934 let pat_shape = cond_shape
935 .offset_left(matcher.len())?
936 .sub_width(self.connector.len())?;
937 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
938 let result = format!("{}{}{}", matcher, pat_string, self.connector);
939 return rewrite_assign_rhs(context, result, expr, cond_shape);
942 let expr_rw = expr.rewrite(context, cond_shape);
943 // The expression may (partially) fit on the current line.
944 // We do not allow splitting between `if` and condition.
945 if self.keyword == "if" || expr_rw.is_some() {
949 // The expression won't fit on the current line, jump to next.
950 let nested_shape = shape
951 .block_indent(context.config.tab_spaces())
952 .with_max_width(context.config);
953 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
954 expr.rewrite(context, nested_shape)
955 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
960 context: &RewriteContext,
963 ) -> Option<(String, usize)> {
964 // Do not take the rhs overhead from the upper expressions into account
965 // when rewriting pattern.
966 let new_width = context.budget(shape.used_width());
967 let fresh_shape = Shape {
971 let constr_shape = if self.nested_if {
972 // We are part of an if-elseif-else chain. Our constraints are tightened.
973 // 7 = "} else " .len()
974 fresh_shape.offset_left(7)?
979 let label_string = rewrite_label(self.label);
980 // 1 = space after keyword.
981 let offset = self.keyword.len() + label_string.len() + 1;
983 let pat_expr_string = match self.cond {
984 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
985 None => String::new(),
989 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
995 let one_line_budget = context
998 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
999 let force_newline_brace = (pat_expr_string.contains('\n')
1000 || pat_expr_string.len() > one_line_budget)
1001 && !last_line_extendable(&pat_expr_string);
1003 // Try to format if-else on single line.
1004 if self.allow_single_line
1008 .single_line_if_else_max_width > 0
1010 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1012 if let Some(cond_str) = trial {
1017 .single_line_if_else_max_width
1019 return Some((cond_str, 0));
1024 let cond_span = if let Some(cond) = self.cond {
1027 mk_sp(self.block.span.lo(), self.block.span.lo())
1030 // `for event in event`
1031 // Do not include label in the span.
1034 .map_or(self.span.lo(), |label| label.ident.span.hi());
1035 let between_kwd_cond = mk_sp(
1038 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1039 if self.pats.is_empty() {
1041 } else if self.matcher.is_empty() {
1042 self.pats[0].span.lo()
1046 .span_before(self.span, self.matcher.trim())
1050 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1052 let after_cond_comment =
1053 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1055 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1057 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1058 || force_newline_brace
1065 let used_width = if pat_expr_string.contains('\n') {
1066 last_line_width(&pat_expr_string)
1068 // 2 = spaces after keyword and condition.
1069 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1077 between_kwd_cond_comment.as_ref().map_or(
1078 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1086 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1093 impl<'a> Rewrite for ControlFlow<'a> {
1094 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1095 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1097 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1098 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1099 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1100 if used_width == 0 {
1101 return Some(cond_str);
1104 let block_width = shape.width.saturating_sub(used_width);
1105 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1106 // we should avoid the single line case.
1107 let block_width = if self.else_block.is_some() || self.nested_if {
1112 let block_shape = Shape {
1117 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1119 rewrite_block_with_visitor(context, "", self.block, None, block_shape, true);
1120 context.is_if_else_block.replace(old_val);
1124 let mut result = format!("{}{}", cond_str, block_str);
1126 if let Some(else_block) = self.else_block {
1127 let shape = Shape::indented(shape.indent, context.config);
1128 let mut last_in_chain = false;
1129 let rewrite = match else_block.node {
1130 // If the else expression is another if-else expression, prevent it
1131 // from being formatted on a single line.
1132 // Note how we're passing the original shape, as the
1133 // cost of "else" should not cascade.
1134 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1135 ControlFlow::new_if(
1137 ptr_vec_to_ref_vec(pat),
1139 next_else_block.as_ref().map(|e| &**e),
1142 mk_sp(else_block.span.lo(), self.span.hi()),
1143 ).rewrite(context, shape)
1145 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1146 ControlFlow::new_if(
1150 next_else_block.as_ref().map(|e| &**e),
1153 mk_sp(else_block.span.lo(), self.span.hi()),
1154 ).rewrite(context, shape)
1157 last_in_chain = true;
1158 // When rewriting a block, the width is only used for single line
1159 // blocks, passing 1 lets us avoid that.
1160 let else_shape = Shape {
1161 width: min(1, shape.width),
1164 format_expr(else_block, ExprType::Statement, context, else_shape)
1168 let between_kwd_else_block = mk_sp(
1169 self.block.span.hi(),
1172 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1174 let between_kwd_else_block_comment =
1175 extract_comment(between_kwd_else_block, context, shape);
1177 let after_else = mk_sp(
1180 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1181 else_block.span.lo(),
1183 let after_else_comment = extract_comment(after_else, context, shape);
1185 let between_sep = match context.config.control_brace_style() {
1186 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1189 ControlBraceStyle::AlwaysSameLine => " ",
1191 let after_sep = match context.config.control_brace_style() {
1192 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1196 result.push_str(&format!(
1198 between_kwd_else_block_comment
1200 .map_or(between_sep, |s| &**s),
1201 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1203 result.push_str(&rewrite?);
1210 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1212 Some(label) => Cow::from(format!("{}: ", label.ident)),
1213 None => Cow::from(""),
1217 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1218 match rewrite_missing_comment(span, shape, context) {
1219 Some(ref comment) if !comment.is_empty() => Some(format!(
1220 "{indent}{}{indent}",
1222 indent = shape.indent.to_string_with_newline(context.config)
1228 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1229 let snippet = codemap.span_to_snippet(block.span).unwrap();
1230 contains_comment(&snippet)
1233 // Checks that a block contains no statements, an expression and no comments or
1235 // FIXME: incorrectly returns false when comment is contained completely within
1237 pub fn is_simple_block(
1239 attrs: Option<&[ast::Attribute]>,
1242 (block.stmts.len() == 1
1243 && stmt_is_expr(&block.stmts[0])
1244 && !block_contains_comment(block, codemap)
1245 && attrs.map_or(true, |a| a.is_empty()))
1248 /// Checks whether a block contains at most one statement or expression, and no
1249 /// comments or attributes.
1250 pub fn is_simple_block_stmt(
1252 attrs: Option<&[ast::Attribute]>,
1255 block.stmts.len() <= 1
1256 && !block_contains_comment(block, codemap)
1257 && attrs.map_or(true, |a| a.is_empty())
1260 /// Checks whether a block contains no statements, expressions, comments, or
1261 /// inner attributes.
1262 pub fn is_empty_block(
1264 attrs: Option<&[ast::Attribute]>,
1267 block.stmts.is_empty()
1268 && !block_contains_comment(block, codemap)
1269 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1272 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1274 ast::StmtKind::Expr(..) => true,
1279 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1280 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1287 pub fn rewrite_multiple_patterns(
1288 context: &RewriteContext,
1291 ) -> Option<String> {
1294 .map(|p| p.rewrite(context, shape))
1295 .collect::<Option<Vec<_>>>()?;
1297 let use_mixed_layout = pats
1299 .zip(pat_strs.iter())
1300 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1301 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1302 let tactic = if use_mixed_layout {
1303 DefinitiveListTactic::Mixed
1307 ListTactic::HorizontalVertical,
1308 Separator::VerticalBar,
1312 let fmt = ListFormatting {
1315 trailing_separator: SeparatorTactic::Never,
1316 separator_place: context.config.binop_separator(),
1318 ends_with_newline: false,
1319 preserve_newline: false,
1320 config: context.config,
1322 write_list(&items, &fmt)
1325 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1327 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1329 context.snippet(l.span).to_owned(),
1330 context.config.max_width(),
1336 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1337 let string_lit = context.snippet(span);
1339 if !context.config.format_strings() {
1344 .all(|line| line.ends_with('\\'))
1346 let new_indent = shape.visual_indent(1).indent;
1347 let indented_string_lit = String::from(
1353 new_indent.to_string(context.config),
1357 .collect::<Vec<_>>()
1361 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1363 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1367 // Remove the quote characters.
1368 let str_lit = &string_lit[1..string_lit.len() - 1];
1372 &StringFormat::new(shape.visual_indent(0), context.config),
1377 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1378 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1379 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1381 .find(|&&(s, _)| s == callee_str)
1383 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1385 Some((all_simple, num_args_before))
1391 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1394 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1395 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1396 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1397 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1398 // format! like macros
1399 // From the Rust Standard Library.
1403 ("format_args!", 0),
1407 ("unreachable!", 0),
1408 // From the `log` crate.
1413 // write! like macros
1415 ("debug_assert!", 1),
1418 // assert_eq! like macros
1421 ("debug_assert_eq!", 2),
1422 ("debug_assert_ne!", 2),
1425 fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<SeparatorTactic> {
1426 if context.inside_macro() {
1427 if span_ends_with_comma(context, span) {
1428 Some(SeparatorTactic::Always)
1430 Some(SeparatorTactic::Never)
1437 pub fn rewrite_call(
1438 context: &RewriteContext,
1440 args: &[ptr::P<ast::Expr>],
1443 ) -> Option<String> {
1444 overflow::rewrite_with_parens(
1447 &ptr_vec_to_ref_vec(args),
1450 context.config.width_heuristics().fn_call_width,
1451 choose_separator_tactic(context, span),
1455 fn is_simple_expr(expr: &ast::Expr) -> bool {
1457 ast::ExprKind::Lit(..) => true,
1458 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1459 ast::ExprKind::AddrOf(_, ref expr)
1460 | ast::ExprKind::Box(ref expr)
1461 | ast::ExprKind::Cast(ref expr, _)
1462 | ast::ExprKind::Field(ref expr, _)
1463 | ast::ExprKind::Try(ref expr)
1464 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1465 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1466 is_simple_expr(lhs) && is_simple_expr(rhs)
1472 pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1475 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1478 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1480 ast::ExprKind::Match(..) => {
1481 (context.use_block_indent() && args_len == 1)
1482 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1484 ast::ExprKind::If(..)
1485 | ast::ExprKind::IfLet(..)
1486 | ast::ExprKind::ForLoop(..)
1487 | ast::ExprKind::Loop(..)
1488 | ast::ExprKind::While(..)
1489 | ast::ExprKind::WhileLet(..) => {
1490 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1492 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1493 context.use_block_indent()
1494 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1496 ast::ExprKind::Array(..)
1497 | ast::ExprKind::Call(..)
1498 | ast::ExprKind::Mac(..)
1499 | ast::ExprKind::MethodCall(..)
1500 | ast::ExprKind::Struct(..)
1501 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1502 ast::ExprKind::AddrOf(_, ref expr)
1503 | ast::ExprKind::Box(ref expr)
1504 | ast::ExprKind::Try(ref expr)
1505 | ast::ExprKind::Unary(_, ref expr)
1506 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1511 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1513 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1514 ast::ExprKind::AddrOf(_, ref expr)
1515 | ast::ExprKind::Box(ref expr)
1516 | ast::ExprKind::Try(ref expr)
1517 | ast::ExprKind::Unary(_, ref expr)
1518 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1523 /// Return true if a function call or a method call represented by the given span ends with a
1524 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1525 /// comma from macro can potentially break the code.
1526 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
1527 let mut result: bool = Default::default();
1528 let mut prev_char: char = Default::default();
1529 let closing_delimiters = &[')', '}', ']'];
1531 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1533 _ if kind.is_comment() || c.is_whitespace() => continue,
1534 c if closing_delimiters.contains(&c) => {
1535 result &= !closing_delimiters.contains(&prev_char);
1537 ',' => result = true,
1538 _ => result = false,
1547 context: &RewriteContext,
1548 mut subexpr: &ast::Expr,
1551 ) -> Option<String> {
1552 debug!("rewrite_paren, shape: {:?}", shape);
1554 // Extract comments within parens.
1555 let mut pre_comment;
1556 let mut post_comment;
1557 let remove_nested_parens = context.config.remove_nested_parens();
1560 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1561 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1562 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1563 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1565 // Remove nested parens if there are no comments.
1566 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1567 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1568 span = subexpr.span;
1569 subexpr = subsubexpr;
1578 let sub_shape = shape.offset_left(1).and_then(|s| s.sub_width(1))?;
1580 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1581 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1584 if subexpr_str.contains('\n') || first_line_width(&subexpr_str) + 2 <= shape.width {
1585 Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
1594 context: &RewriteContext,
1596 ) -> Option<String> {
1597 let expr_str = expr.rewrite(context, shape)?;
1599 let offset = last_line_width(&expr_str) + 1;
1600 let rhs_overhead = shape.rhs_overhead(context.config);
1601 let index_shape = if expr_str.contains('\n') {
1602 Shape::legacy(context.config.max_width(), shape.indent)
1603 .offset_left(offset)
1604 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1606 shape.visual_indent(offset).sub_width(offset + 1)
1608 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1610 // Return if index fits in a single line.
1611 match orig_index_rw {
1612 Some(ref index_str) if !index_str.contains('\n') => {
1613 return Some(format!("{}[{}]", expr_str, index_str));
1618 // Try putting index on the next line and see if it fits in a single line.
1619 let indent = shape.indent.block_indent(context.config);
1620 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1621 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1622 let new_index_rw = index.rewrite(context, index_shape);
1623 match (orig_index_rw, new_index_rw) {
1624 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1627 indent.to_string_with_newline(context.config),
1630 (None, Some(ref new_index_str)) => Some(format!(
1633 indent.to_string_with_newline(context.config),
1636 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1641 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
1646 fields.iter().all(|field| !field.is_shorthand)
1649 fn rewrite_struct_lit<'a>(
1650 context: &RewriteContext,
1652 fields: &'a [ast::Field],
1653 base: Option<&'a ast::Expr>,
1656 ) -> Option<String> {
1657 debug!("rewrite_struct_lit: shape {:?}", shape);
1659 enum StructLitField<'a> {
1660 Regular(&'a ast::Field),
1661 Base(&'a ast::Expr),
1665 let path_shape = shape.sub_width(2)?;
1666 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1668 if fields.is_empty() && base.is_none() {
1669 return Some(format!("{} {{}}", path_str));
1672 // Foo { a: Foo } - indent is +3, width is -5.
1673 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1675 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1676 let body_lo = context.snippet_provider.span_after(span, "{");
1677 let fields_str = if struct_lit_can_be_aligned(fields, &base)
1678 && context.config.struct_field_align_threshold() > 0
1680 rewrite_with_alignment(
1684 mk_sp(body_lo, span.hi()),
1688 let field_iter = fields
1690 .map(StructLitField::Regular)
1691 .chain(base.into_iter().map(StructLitField::Base));
1693 let span_lo = |item: &StructLitField| match *item {
1694 StructLitField::Regular(field) => field.span().lo(),
1695 StructLitField::Base(expr) => {
1696 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1697 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1698 let pos = snippet.find_uncommented("..").unwrap();
1699 last_field_hi + BytePos(pos as u32)
1702 let span_hi = |item: &StructLitField| match *item {
1703 StructLitField::Regular(field) => field.span().hi(),
1704 StructLitField::Base(expr) => expr.span.hi(),
1706 let rewrite = |item: &StructLitField| match *item {
1707 StructLitField::Regular(field) => {
1708 // The 1 taken from the v_budget is for the comma.
1709 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1711 StructLitField::Base(expr) => {
1713 expr.rewrite(context, v_shape.offset_left(2)?)
1714 .map(|s| format!("..{}", s))
1718 let items = itemize_list(
1719 context.snippet_provider,
1730 let item_vec = items.collect::<Vec<_>>();
1732 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1733 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1735 let ends_with_comma = span_ends_with_comma(context, span);
1736 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1738 let fmt = struct_lit_formatting(
1742 force_no_trailing_comma || base.is_some(),
1745 write_list(&item_vec, &fmt)?
1748 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1749 Some(format!("{} {{{}}}", path_str, fields_str))
1751 // FIXME if context.config.indent_style() == Visual, but we run out
1752 // of space, we should fall back to BlockIndent.
1755 pub fn wrap_struct_field(
1756 context: &RewriteContext,
1759 nested_shape: Shape,
1760 one_line_width: usize,
1762 if context.config.indent_style() == IndentStyle::Block
1763 && (fields_str.contains('\n')
1764 || !context.config.struct_lit_single_line()
1765 || fields_str.len() > one_line_width)
1769 nested_shape.indent.to_string_with_newline(context.config),
1771 shape.indent.to_string_with_newline(context.config)
1774 // One liner or visual indent.
1775 format!(" {} ", fields_str)
1779 pub fn struct_lit_field_separator(config: &Config) -> &str {
1780 colon_spaces(config.space_before_colon(), config.space_after_colon())
1783 pub fn rewrite_field(
1784 context: &RewriteContext,
1787 prefix_max_width: usize,
1788 ) -> Option<String> {
1789 if contains_skip(&field.attrs) {
1790 return Some(context.snippet(field.span()).to_owned());
1792 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1793 if !attrs_str.is_empty() {
1794 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1796 let name = &field.ident.name.to_string();
1797 if field.is_shorthand {
1798 Some(attrs_str + &name)
1800 let mut separator = String::from(struct_lit_field_separator(context.config));
1801 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1802 separator.push(' ');
1804 let overhead = name.len() + separator.len();
1805 let expr_shape = shape.offset_left(overhead)?;
1806 let expr = field.expr.rewrite(context, expr_shape);
1809 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1810 Some(attrs_str + &name)
1812 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1814 let expr_offset = shape.indent.block_indent(context.config);
1817 .rewrite(context, Shape::indented(expr_offset, context.config));
1823 expr_offset.to_string(context.config),
1832 fn rewrite_tuple_in_visual_indent_style<'a, T>(
1833 context: &RewriteContext,
1839 T: Rewrite + Spanned + ToExpr + 'a,
1841 let mut items = items.iter();
1842 // In case of length 1, need a trailing comma
1843 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1844 if items.len() == 1 {
1846 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1850 .rewrite(context, nested_shape)
1851 .map(|s| format!("({},)", s));
1854 let list_lo = context.snippet_provider.span_after(span, "(");
1855 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1856 let items = itemize_list(
1857 context.snippet_provider,
1861 |item| item.span().lo(),
1862 |item| item.span().hi(),
1863 |item| item.rewrite(context, nested_shape),
1865 span.hi() - BytePos(1),
1868 let item_vec: Vec<_> = items.collect();
1869 let tactic = definitive_tactic(
1871 ListTactic::HorizontalVertical,
1875 let fmt = ListFormatting {
1878 trailing_separator: SeparatorTactic::Never,
1879 separator_place: SeparatorPlace::Back,
1881 ends_with_newline: false,
1882 preserve_newline: false,
1883 config: context.config,
1885 let list_str = write_list(&item_vec, &fmt)?;
1887 Some(format!("({})", list_str))
1890 pub fn rewrite_tuple<'a, T>(
1891 context: &RewriteContext,
1897 T: Rewrite + Spanned + ToExpr + 'a,
1899 debug!("rewrite_tuple {:?}", shape);
1900 if context.use_block_indent() {
1901 // We use the same rule as function calls for rewriting tuples.
1902 let force_tactic = if context.inside_macro() {
1903 if span_ends_with_comma(context, span) {
1904 Some(SeparatorTactic::Always)
1906 Some(SeparatorTactic::Never)
1908 } else if items.len() == 1 {
1909 Some(SeparatorTactic::Always)
1913 overflow::rewrite_with_parens(
1919 context.config.width_heuristics().fn_call_width,
1923 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
1927 pub fn rewrite_unary_prefix<R: Rewrite>(
1928 context: &RewriteContext,
1932 ) -> Option<String> {
1934 .rewrite(context, shape.offset_left(prefix.len())?)
1935 .map(|r| format!("{}{}", prefix, r))
1938 // FIXME: this is probably not correct for multi-line Rewrites. we should
1939 // subtract suffix.len() from the last line budget, not the first!
1940 pub fn rewrite_unary_suffix<R: Rewrite>(
1941 context: &RewriteContext,
1945 ) -> Option<String> {
1947 .rewrite(context, shape.sub_width(suffix.len())?)
1954 fn rewrite_unary_op(
1955 context: &RewriteContext,
1959 ) -> Option<String> {
1960 // For some reason, an UnOp is not spanned like BinOp!
1961 let operator_str = match *op {
1962 ast::UnOp::Deref => "*",
1963 ast::UnOp::Not => "!",
1964 ast::UnOp::Neg => "-",
1966 rewrite_unary_prefix(context, operator_str, expr, shape)
1969 fn rewrite_assignment(
1970 context: &RewriteContext,
1973 op: Option<&ast::BinOp>,
1975 ) -> Option<String> {
1976 let operator_str = match op {
1977 Some(op) => context.snippet(op.span),
1981 // 1 = space between lhs and operator.
1982 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1983 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1985 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1988 /// Controls where to put the rhs.
1989 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1990 pub enum RhsTactics {
1993 /// Put the rhs on the next line if it uses multiple line.
1997 // The left hand side must contain everything up to, and including, the
1998 // assignment operator.
1999 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2000 context: &RewriteContext,
2004 ) -> Option<String> {
2005 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
2008 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2009 context: &RewriteContext,
2013 rhs_tactics: RhsTactics,
2014 ) -> Option<String> {
2015 let lhs = lhs.into();
2016 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
2017 shape.indent.width()
2021 // 1 = space between operator and rhs.
2022 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2024 offset: shape.offset + last_line_width + 1,
2027 let rhs = choose_rhs(
2031 ex.rewrite(context, orig_shape),
2037 fn choose_rhs<R: Rewrite>(
2038 context: &RewriteContext,
2041 orig_rhs: Option<String>,
2042 rhs_tactics: RhsTactics,
2043 ) -> Option<String> {
2045 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2046 Some(format!(" {}", new_str))
2049 // Expression did not fit on the same line as the identifier.
2050 // Try splitting the line and see if that works better.
2052 Shape::indented(shape.indent.block_indent(context.config), context.config)
2053 .sub_width(shape.rhs_overhead(context.config))?;
2054 let new_rhs = expr.rewrite(context, new_shape);
2055 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2057 match (orig_rhs, new_rhs) {
2058 (Some(ref orig_rhs), Some(ref new_rhs))
2059 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2062 Some(format!(" {}", orig_rhs))
2064 (Some(ref orig_rhs), Some(ref new_rhs))
2065 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2067 Some(format!("{}{}", new_indent_str, new_rhs))
2069 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2070 (None, None) => None,
2071 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2077 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2078 rhs_tactics == RhsTactics::ForceNextLine
2079 || !next_line_rhs.contains('\n')
2080 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2083 fn rewrite_expr_addrof(
2084 context: &RewriteContext,
2085 mutability: ast::Mutability,
2088 ) -> Option<String> {
2089 let operator_str = match mutability {
2090 ast::Mutability::Immutable => "&",
2091 ast::Mutability::Mutable => "&mut ",
2093 rewrite_unary_prefix(context, operator_str, expr, shape)
2097 fn to_expr(&self) -> Option<&ast::Expr>;
2098 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2101 impl ToExpr for ast::Expr {
2102 fn to_expr(&self) -> Option<&ast::Expr> {
2106 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2107 can_be_overflowed_expr(context, self, len)
2111 impl ToExpr for ast::Ty {
2112 fn to_expr(&self) -> Option<&ast::Expr> {
2116 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2117 can_be_overflowed_type(context, self, len)
2121 impl<'a> ToExpr for TuplePatField<'a> {
2122 fn to_expr(&self) -> Option<&ast::Expr> {
2126 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2127 can_be_overflowed_pat(context, self, len)
2131 impl<'a> ToExpr for ast::StructField {
2132 fn to_expr(&self) -> Option<&ast::Expr> {
2136 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2141 impl<'a> ToExpr for MacroArg {
2142 fn to_expr(&self) -> Option<&ast::Expr> {
2144 MacroArg::Expr(ref expr) => Some(expr),
2149 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2151 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2152 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2153 MacroArg::Pat(..) => false,
2154 MacroArg::Item(..) => len == 1,
2159 impl ToExpr for ast::GenericParam {
2160 fn to_expr(&self) -> Option<&ast::Expr> {
2164 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {