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};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23 rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, ListFormatting, ListItem, Separator};
27 use macros::{rewrite_macro, MacroArg, MacroPosition};
28 use matches::rewrite_match;
30 use patterns::{can_be_overflowed_pat, is_short_pattern, TuplePatField};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
34 use string::{rewrite_string, StringFormat};
35 use types::{can_be_overflowed_type, rewrite_path, PathContext};
36 use utils::{colon_spaces, contains_skip, count_newlines, first_line_width, inner_attributes,
37 last_line_extendable, last_line_width, mk_sp, outer_attributes, paren_overhead,
38 ptr_vec_to_ref_vec, semicolon_for_stmt, wrap_str};
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
42 impl Rewrite for ast::Expr {
43 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44 format_expr(self, ExprType::SubExpression, context, shape)
48 #[derive(Copy, Clone, PartialEq)]
57 context: &RewriteContext,
60 skip_out_of_file_lines_range!(context, expr.span);
62 if contains_skip(&*expr.attrs) {
63 return Some(context.snippet(expr.span()).to_owned());
66 let expr_rw = match expr.node {
67 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
69 &ptr_vec_to_ref_vec(expr_vec),
76 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
77 ast::ExprKind::Call(ref callee, ref args) => {
78 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
79 let callee_str = callee.rewrite(context, shape)?;
80 rewrite_call(context, &callee_str, args, inner_span, shape)
82 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
83 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
84 // FIXME: format comments between operands and operator
88 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
91 context.config.binop_separator(),
94 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
95 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
99 base.as_ref().map(|e| &**e),
103 ast::ExprKind::Tup(ref items) => {
104 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
106 ast::ExprKind::If(..)
107 | ast::ExprKind::IfLet(..)
108 | ast::ExprKind::ForLoop(..)
109 | ast::ExprKind::Loop(..)
110 | ast::ExprKind::While(..)
111 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
112 .and_then(|control_flow| control_flow.rewrite(context, shape)),
113 ast::ExprKind::Block(ref block) => {
115 ExprType::Statement => {
116 if is_unsafe_block(block) {
117 rewrite_block(block, Some(&expr.attrs), context, shape)
118 } else if let rw @ Some(_) =
119 rewrite_empty_block(context, block, Some(&expr.attrs), "", shape)
121 // Rewrite block without trying to put it in a single line.
124 let prefix = block_prefix(context, block, shape)?;
125 rewrite_block_with_visitor(
135 ExprType::SubExpression => rewrite_block(block, Some(&expr.attrs), context, shape),
138 ast::ExprKind::Match(ref cond, ref arms) => {
139 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
141 ast::ExprKind::Path(ref qself, ref path) => {
142 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
144 ast::ExprKind::Assign(ref lhs, ref rhs) => {
145 rewrite_assignment(context, lhs, rhs, None, shape)
147 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
148 rewrite_assignment(context, lhs, rhs, Some(op), shape)
150 ast::ExprKind::Continue(ref opt_label) => {
151 let id_str = match *opt_label {
152 Some(label) => format!(" {}", label.ident),
153 None => String::new(),
155 Some(format!("continue{}", id_str))
157 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
158 let id_str = match *opt_label {
159 Some(label) => format!(" {}", label.ident),
160 None => String::new(),
163 if let Some(ref expr) = *opt_expr {
164 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
166 Some(format!("break{}", id_str))
169 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
170 rewrite_unary_prefix(context, "yield ", &**expr, shape)
172 Some("yield".to_string())
174 ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
175 closures::rewrite_closure(
176 capture, movability, fn_decl, body, expr.span, context, shape,
179 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
180 rewrite_chain(expr, context, shape)
182 ast::ExprKind::Mac(ref mac) => {
183 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
185 context.snippet(expr.span).to_owned(),
186 context.config.max_width(),
191 ast::ExprKind::Ret(None) => Some("return".to_owned()),
192 ast::ExprKind::Ret(Some(ref expr)) => {
193 rewrite_unary_prefix(context, "return ", &**expr, shape)
195 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
196 ast::ExprKind::AddrOf(mutability, ref expr) => {
197 rewrite_expr_addrof(context, mutability, expr, shape)
199 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
202 PairParts::new("", " as ", ""),
205 SeparatorPlace::Front,
207 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
210 PairParts::new("", ": ", ""),
213 SeparatorPlace::Back,
215 ast::ExprKind::Index(ref expr, ref index) => {
216 rewrite_index(&**expr, &**index, context, shape)
218 ast::ExprKind::Repeat(ref expr, ref repeats) => {
219 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
227 PairParts::new(lbr, "; ", rbr),
230 SeparatorPlace::Back,
233 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
234 let delim = match limits {
235 ast::RangeLimits::HalfOpen => "..",
236 ast::RangeLimits::Closed => "..=",
239 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
241 ast::ExprKind::Lit(ref lit) => match lit.node {
242 ast::LitKind::FloatUnsuffixed(..) => {
243 context.snippet(lit.span).ends_with('.')
251 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
253 // Don't format `.. ..` into `....`, which is invalid.
255 // This check is unnecessary for `lhs`, because a range
256 // starting from another range needs parentheses as `(x ..) ..`
257 // (`x .. ..` is a range from `x` to `..`).
258 ast::ExprKind::Range(None, _, _) => true,
263 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
264 let space_if = |b: bool| if b { " " } else { "" };
268 lhs.map(|lhs| space_if(needs_space_before_range(context, lhs)))
271 rhs.map(|rhs| space_if(needs_space_after_range(rhs)))
276 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
277 (Some(lhs), Some(rhs)) => {
278 let sp_delim = if context.config.spaces_around_ranges() {
279 format!(" {} ", delim)
281 default_sp_delim(Some(lhs), Some(rhs))
286 PairParts::new("", &sp_delim, ""),
289 context.config.binop_separator(),
292 (None, Some(rhs)) => {
293 let sp_delim = if context.config.spaces_around_ranges() {
294 format!("{} ", delim)
296 default_sp_delim(None, Some(rhs))
298 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
300 (Some(lhs), None) => {
301 let sp_delim = if context.config.spaces_around_ranges() {
302 format!(" {}", delim)
304 default_sp_delim(Some(lhs), None)
306 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
308 (None, None) => Some(delim.to_owned()),
311 // We do not format these expressions yet, but they should still
312 // satisfy our width restrictions.
313 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
314 ast::ExprKind::Catch(ref block) => {
315 if let rw @ Some(_) =
316 rewrite_single_line_block(context, "do catch ", block, Some(&expr.attrs), shape)
321 let budget = shape.width.checked_sub(9).unwrap_or(0);
329 Shape::legacy(budget, shape.indent)
337 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
338 .and_then(|expr_str| {
339 let attrs = outer_attributes(&expr.attrs);
340 let attrs_str = attrs.rewrite(context, shape)?;
342 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
345 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
349 #[derive(new, Clone, Copy)]
350 pub struct PairParts<'a> {
356 pub fn rewrite_pair<LHS, RHS>(
360 context: &RewriteContext,
362 separator_place: SeparatorPlace,
368 let lhs_overhead = match separator_place {
369 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
370 SeparatorPlace::Front => shape.used_width(),
372 let lhs_shape = Shape {
373 width: context.budget(lhs_overhead),
376 let lhs_result = lhs.rewrite(context, lhs_shape)
377 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
379 // Try to put both lhs and rhs on the same line.
380 let rhs_orig_result = shape
381 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
382 .and_then(|s| s.sub_width(pp.suffix.len()))
383 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
384 if let Some(ref rhs_result) = rhs_orig_result {
385 // If the length of the lhs is equal to or shorter than the tab width or
386 // the rhs looks like block expression, we put the rhs on the same
387 // line with the lhs even if the rhs is multi-lined.
388 let allow_same_line = lhs_result.len() <= context.config.tab_spaces()
392 .map(|first_line| first_line.ends_with('{'))
394 if !rhs_result.contains('\n') || allow_same_line {
395 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
396 + first_line_width(rhs_result) + pp.suffix.len();
397 if one_line_width <= shape.width {
400 lhs_result, pp.infix, rhs_result, pp.suffix
406 // We have to use multiple lines.
407 // Re-evaluate the rhs because we have more space now:
408 let mut rhs_shape = match context.config.indent_style() {
409 IndentStyle::Visual => shape
410 .sub_width(pp.suffix.len() + pp.prefix.len())?
411 .visual_indent(pp.prefix.len()),
412 IndentStyle::Block => {
413 // Try to calculate the initial constraint on the right hand side.
414 let rhs_overhead = shape.rhs_overhead(context.config);
415 Shape::indented(shape.indent.block_indent(context.config), context.config)
416 .sub_width(rhs_overhead)?
419 let infix = match separator_place {
420 SeparatorPlace::Back => pp.infix.trim_right(),
421 SeparatorPlace::Front => pp.infix.trim_left(),
423 if separator_place == SeparatorPlace::Front {
424 rhs_shape = rhs_shape.offset_left(infix.len())?;
426 let rhs_result = rhs.rewrite(context, rhs_shape)?;
427 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
428 let infix_with_sep = match separator_place {
429 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
430 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
434 lhs_result, infix_with_sep, rhs_result, pp.suffix
438 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
442 context: &RewriteContext,
444 force_separator_tactic: Option<SeparatorTactic>,
445 delim_token: Option<DelimToken>,
446 ) -> Option<String> {
447 overflow::rewrite_with_square_brackets(
453 force_separator_tactic,
458 fn rewrite_empty_block(
459 context: &RewriteContext,
461 attrs: Option<&[ast::Attribute]>,
464 ) -> Option<String> {
465 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
469 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
471 return Some(format!("{}{{}}", prefix));
474 // If a block contains only a single-line comment, then leave it on one line.
475 let user_str = context.snippet(block.span);
476 let user_str = user_str.trim();
477 if user_str.starts_with('{') && user_str.ends_with('}') {
478 let comment_str = user_str[1..user_str.len() - 1].trim();
479 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
480 && comment_str.len() + 4 <= shape.width
482 return Some(format!("{}{{ {} }}", prefix, comment_str));
489 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
490 Some(match block.rules {
491 ast::BlockCheckMode::Unsafe(..) => {
492 let snippet = context.snippet(block.span);
493 let open_pos = snippet.find_uncommented("{")?;
494 // Extract comment between unsafe and block start.
495 let trimmed = &snippet[6..open_pos].trim();
497 if !trimmed.is_empty() {
498 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
499 let budget = shape.width.checked_sub(9)?;
505 Shape::legacy(budget, shape.indent + 7),
513 ast::BlockCheckMode::Default => String::new(),
517 fn rewrite_single_line_block(
518 context: &RewriteContext,
521 attrs: Option<&[ast::Attribute]>,
523 ) -> Option<String> {
524 if is_simple_block(block, attrs, context.codemap) {
525 let expr_shape = shape.offset_left(last_line_width(prefix))?;
526 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
527 let result = format!("{}{{ {} }}", prefix, expr_str);
528 if result.len() <= shape.width && !result.contains('\n') {
535 pub fn rewrite_block_with_visitor(
536 context: &RewriteContext,
539 attrs: Option<&[ast::Attribute]>,
542 ) -> Option<String> {
543 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, prefix, shape) {
547 let mut visitor = FmtVisitor::from_context(context);
548 visitor.block_indent = shape.indent;
549 visitor.is_if_else_block = context.is_if_else_block();
551 ast::BlockCheckMode::Unsafe(..) => {
552 let snippet = context.snippet(block.span);
553 let open_pos = snippet.find_uncommented("{")?;
554 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
556 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
559 let inner_attrs = attrs.map(inner_attributes);
560 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
561 Some(format!("{}{}", prefix, visitor.buffer))
564 impl Rewrite for ast::Block {
565 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
566 rewrite_block(self, None, context, shape)
572 attrs: Option<&[ast::Attribute]>,
573 context: &RewriteContext,
575 ) -> Option<String> {
576 let prefix = block_prefix(context, block, shape)?;
578 // shape.width is used only for the single line case: either the empty block `{}`,
579 // or an unsafe expression `unsafe { e }`.
580 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, &prefix, shape) {
584 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, shape, true);
585 if let Some(ref result_str) = result {
586 if result_str.lines().count() <= 3 {
587 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, block, attrs, shape) {
596 impl Rewrite for ast::Stmt {
597 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
598 skip_out_of_file_lines_range!(context, self.span());
600 let result = match self.node {
601 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
602 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
603 let suffix = if semicolon_for_stmt(context, self) {
609 let shape = shape.sub_width(suffix.len())?;
610 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
612 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
614 result.and_then(|res| recover_comment_removed(res, self.span(), context))
618 // Rewrite condition if the given expression has one.
619 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
621 ast::ExprKind::Match(ref cond, _) => {
623 let cond_shape = match context.config.indent_style() {
624 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
625 IndentStyle::Block => shape.offset_left(8)?,
627 cond.rewrite(context, cond_shape)
629 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
631 String::from("\n") + &shape.indent.block_only().to_string(context.config);
633 .rewrite_cond(context, shape, &alt_block_sep)
634 .and_then(|rw| Some(rw.0))
639 // Abstraction over control flow expressions
641 struct ControlFlow<'a> {
642 cond: Option<&'a ast::Expr>,
643 block: &'a ast::Block,
644 else_block: Option<&'a ast::Expr>,
645 label: Option<ast::Label>,
646 pats: Vec<&'a ast::Pat>,
650 allow_single_line: bool,
651 // True if this is an `if` expression in an `else if` :-( hacky
656 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
658 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
662 else_block.as_ref().map(|e| &**e),
663 expr_type == ExprType::SubExpression,
667 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
668 Some(ControlFlow::new_if(
670 ptr_vec_to_ref_vec(pat),
672 else_block.as_ref().map(|e| &**e),
673 expr_type == ExprType::SubExpression,
678 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
679 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
681 ast::ExprKind::Loop(ref block, label) => {
682 Some(ControlFlow::new_loop(block, label, expr.span))
684 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
691 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
692 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
698 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
706 impl<'a> ControlFlow<'a> {
709 pats: Vec<&'a ast::Pat>,
710 block: &'a ast::Block,
711 else_block: Option<&'a ast::Expr>,
712 allow_single_line: bool,
715 ) -> ControlFlow<'a> {
716 let matcher = choose_matcher(&pats);
732 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
742 allow_single_line: false,
749 pats: Vec<&'a ast::Pat>,
751 block: &'a ast::Block,
752 label: Option<ast::Label>,
754 ) -> ControlFlow<'a> {
755 let matcher = choose_matcher(&pats);
765 allow_single_line: false,
774 block: &'a ast::Block,
775 label: Option<ast::Label>,
777 ) -> ControlFlow<'a> {
787 allow_single_line: false,
793 fn rewrite_single_line(
796 context: &RewriteContext,
798 ) -> Option<String> {
799 assert!(self.allow_single_line);
800 let else_block = self.else_block?;
801 let fixed_cost = self.keyword.len() + " { } else { }".len();
803 if let ast::ExprKind::Block(ref else_node) = else_block.node {
804 if !is_simple_block(self.block, None, context.codemap)
805 || !is_simple_block(else_node, None, context.codemap)
806 || pat_expr_str.contains('\n')
811 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
812 let expr = &self.block.stmts[0];
813 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
815 let new_width = new_width.checked_sub(if_str.len())?;
816 let else_expr = &else_node.stmts[0];
817 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
819 if if_str.contains('\n') || else_str.contains('\n') {
823 let result = format!(
824 "{} {} {{ {} }} else {{ {} }}",
825 self.keyword, pat_expr_str, if_str, else_str
828 if result.len() <= width {
837 impl<'a> ControlFlow<'a> {
840 context: &RewriteContext,
844 ) -> Option<String> {
845 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
847 let cond_shape = shape.offset_left(offset)?;
848 if !self.pats.is_empty() {
849 let matcher = if self.matcher.is_empty() {
850 self.matcher.to_owned()
852 format!("{} ", self.matcher)
854 let pat_shape = cond_shape
855 .offset_left(matcher.len())?
856 .sub_width(self.connector.len())?;
857 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
858 let result = format!("{}{}{}", matcher, pat_string, self.connector);
859 return rewrite_assign_rhs(context, result, expr, cond_shape);
862 let expr_rw = expr.rewrite(context, cond_shape);
863 // The expression may (partially) fit on the current line.
864 // We do not allow splitting between `if` and condition.
865 if self.keyword == "if" || expr_rw.is_some() {
869 // The expression won't fit on the current line, jump to next.
870 let nested_shape = shape
871 .block_indent(context.config.tab_spaces())
872 .with_max_width(context.config);
873 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
874 expr.rewrite(context, nested_shape)
875 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
880 context: &RewriteContext,
883 ) -> Option<(String, usize)> {
884 // Do not take the rhs overhead from the upper expressions into account
885 // when rewriting pattern.
886 let new_width = context.budget(shape.used_width());
887 let fresh_shape = Shape {
891 let constr_shape = if self.nested_if {
892 // We are part of an if-elseif-else chain. Our constraints are tightened.
893 // 7 = "} else " .len()
894 fresh_shape.offset_left(7)?
899 let label_string = rewrite_label(self.label);
900 // 1 = space after keyword.
901 let offset = self.keyword.len() + label_string.len() + 1;
903 let pat_expr_string = match self.cond {
904 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
905 None => String::new(),
909 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
915 let one_line_budget = context
918 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
920 let force_newline_brace = (pat_expr_string.contains('\n')
921 || pat_expr_string.len() > one_line_budget)
922 && !last_line_extendable(&pat_expr_string);
924 // Try to format if-else on single line.
925 if self.allow_single_line
929 .single_line_if_else_max_width > 0
931 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
933 if let Some(cond_str) = trial {
938 .single_line_if_else_max_width
940 return Some((cond_str, 0));
945 let cond_span = if let Some(cond) = self.cond {
948 mk_sp(self.block.span.lo(), self.block.span.lo())
951 // `for event in event`
952 // Do not include label in the span.
954 .map_or(self.span.lo(), |label| label.ident.span.hi());
955 let between_kwd_cond = mk_sp(
958 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
959 if self.pats.is_empty() {
961 } else if self.matcher.is_empty() {
962 self.pats[0].span.lo()
966 .span_before(self.span, self.matcher.trim())
970 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
972 let after_cond_comment =
973 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
975 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
977 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
978 || force_newline_brace
985 let used_width = if pat_expr_string.contains('\n') {
986 last_line_width(&pat_expr_string)
988 // 2 = spaces after keyword and condition.
989 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
997 between_kwd_cond_comment.as_ref().map_or(
998 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1006 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1013 impl<'a> Rewrite for ControlFlow<'a> {
1014 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1015 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1017 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1018 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1019 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1020 if used_width == 0 {
1021 return Some(cond_str);
1024 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1025 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1026 // we should avoid the single line case.
1027 let block_width = if self.else_block.is_some() || self.nested_if {
1032 let block_shape = Shape {
1037 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1039 rewrite_block_with_visitor(context, "", self.block, None, block_shape, true);
1040 context.is_if_else_block.replace(old_val);
1044 let mut result = format!("{}{}", cond_str, block_str);
1046 if let Some(else_block) = self.else_block {
1047 let shape = Shape::indented(shape.indent, context.config);
1048 let mut last_in_chain = false;
1049 let rewrite = match else_block.node {
1050 // If the else expression is another if-else expression, prevent it
1051 // from being formatted on a single line.
1052 // Note how we're passing the original shape, as the
1053 // cost of "else" should not cascade.
1054 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1055 ControlFlow::new_if(
1057 ptr_vec_to_ref_vec(pat),
1059 next_else_block.as_ref().map(|e| &**e),
1062 mk_sp(else_block.span.lo(), self.span.hi()),
1063 ).rewrite(context, shape)
1065 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1066 ControlFlow::new_if(
1070 next_else_block.as_ref().map(|e| &**e),
1073 mk_sp(else_block.span.lo(), self.span.hi()),
1074 ).rewrite(context, shape)
1077 last_in_chain = true;
1078 // When rewriting a block, the width is only used for single line
1079 // blocks, passing 1 lets us avoid that.
1080 let else_shape = Shape {
1081 width: min(1, shape.width),
1084 format_expr(else_block, ExprType::Statement, context, else_shape)
1088 let between_kwd_else_block = mk_sp(
1089 self.block.span.hi(),
1092 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1094 let between_kwd_else_block_comment =
1095 extract_comment(between_kwd_else_block, context, shape);
1097 let after_else = mk_sp(
1100 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1101 else_block.span.lo(),
1103 let after_else_comment = extract_comment(after_else, context, shape);
1105 let between_sep = match context.config.control_brace_style() {
1106 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1109 ControlBraceStyle::AlwaysSameLine => " ",
1111 let after_sep = match context.config.control_brace_style() {
1112 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1116 result.push_str(&format!(
1118 between_kwd_else_block_comment
1120 .map_or(between_sep, |s| &**s),
1121 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1123 result.push_str(&rewrite?);
1130 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1132 Some(label) => Cow::from(format!("{}: ", label.ident)),
1133 None => Cow::from(""),
1137 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1138 match rewrite_missing_comment(span, shape, context) {
1139 Some(ref comment) if !comment.is_empty() => Some(format!(
1140 "{indent}{}{indent}",
1142 indent = shape.indent.to_string_with_newline(context.config)
1148 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1149 let snippet = codemap.span_to_snippet(block.span).unwrap();
1150 contains_comment(&snippet)
1153 // Checks that a block contains no statements, an expression and no comments or
1155 // FIXME: incorrectly returns false when comment is contained completely within
1157 pub fn is_simple_block(
1159 attrs: Option<&[ast::Attribute]>,
1162 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1163 && !block_contains_comment(block, codemap) && attrs.map_or(true, |a| a.is_empty()))
1166 /// Checks whether a block contains at most one statement or expression, and no
1167 /// comments or attributes.
1168 pub fn is_simple_block_stmt(
1170 attrs: Option<&[ast::Attribute]>,
1173 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1174 && attrs.map_or(true, |a| a.is_empty())
1177 /// Checks whether a block contains no statements, expressions, comments, or
1178 /// inner attributes.
1179 pub fn is_empty_block(
1181 attrs: Option<&[ast::Attribute]>,
1184 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1185 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1188 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1190 ast::StmtKind::Expr(..) => true,
1195 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1196 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1203 pub fn rewrite_multiple_patterns(
1204 context: &RewriteContext,
1207 ) -> Option<String> {
1208 let pat_strs = pats.iter()
1209 .map(|p| p.rewrite(context, shape))
1210 .collect::<Option<Vec<_>>>()?;
1212 let use_mixed_layout = pats.iter()
1213 .zip(pat_strs.iter())
1214 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1215 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1216 let tactic = if use_mixed_layout {
1217 DefinitiveListTactic::Mixed
1221 ListTactic::HorizontalVertical,
1222 Separator::VerticalBar,
1226 let fmt = ListFormatting {
1229 trailing_separator: SeparatorTactic::Never,
1230 separator_place: context.config.binop_separator(),
1232 ends_with_newline: false,
1233 preserve_newline: false,
1234 config: context.config,
1236 write_list(&items, &fmt)
1239 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1241 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1243 context.snippet(l.span).to_owned(),
1244 context.config.max_width(),
1250 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1251 let string_lit = context.snippet(span);
1253 if !context.config.format_strings() {
1258 .all(|line| line.ends_with('\\'))
1260 let new_indent = shape.visual_indent(1).indent;
1261 let indented_string_lit = String::from(
1267 new_indent.to_string(context.config),
1271 .collect::<Vec<_>>()
1275 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1277 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1281 // Remove the quote characters.
1282 let str_lit = &string_lit[1..string_lit.len() - 1];
1286 &StringFormat::new(shape.visual_indent(0), context.config),
1291 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1292 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1293 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1295 .find(|&&(s, _)| s == callee_str)
1297 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1299 Some((all_simple, num_args_before))
1305 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1308 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1309 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1310 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1311 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1312 // format! like macros
1313 // From the Rust Standard Library.
1317 ("format_args!", 0),
1321 ("unreachable!", 0),
1322 // From the `log` crate.
1327 // write! like macros
1329 ("debug_assert!", 1),
1332 // assert_eq! like macros
1335 ("debug_assert_eq!", 2),
1336 ("debug_assert_ne!", 2),
1339 pub fn rewrite_call(
1340 context: &RewriteContext,
1342 args: &[ptr::P<ast::Expr>],
1345 ) -> Option<String> {
1346 overflow::rewrite_with_parens(
1349 &ptr_vec_to_ref_vec(args),
1352 context.config.width_heuristics().fn_call_width,
1353 if context.inside_macro() {
1354 if span_ends_with_comma(context, span) {
1355 Some(SeparatorTactic::Always)
1357 Some(SeparatorTactic::Never)
1365 fn is_simple_expr(expr: &ast::Expr) -> bool {
1367 ast::ExprKind::Lit(..) => true,
1368 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1369 ast::ExprKind::AddrOf(_, ref expr)
1370 | ast::ExprKind::Box(ref expr)
1371 | ast::ExprKind::Cast(ref expr, _)
1372 | ast::ExprKind::Field(ref expr, _)
1373 | ast::ExprKind::Try(ref expr)
1374 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1375 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1376 is_simple_expr(lhs) && is_simple_expr(rhs)
1382 pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1385 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1388 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1390 ast::ExprKind::Match(..) => {
1391 (context.use_block_indent() && args_len == 1)
1392 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1394 ast::ExprKind::If(..)
1395 | ast::ExprKind::IfLet(..)
1396 | ast::ExprKind::ForLoop(..)
1397 | ast::ExprKind::Loop(..)
1398 | ast::ExprKind::While(..)
1399 | ast::ExprKind::WhileLet(..) => {
1400 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1402 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1403 context.use_block_indent()
1404 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1406 ast::ExprKind::Array(..)
1407 | ast::ExprKind::Call(..)
1408 | ast::ExprKind::Mac(..)
1409 | ast::ExprKind::MethodCall(..)
1410 | ast::ExprKind::Struct(..)
1411 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1412 ast::ExprKind::AddrOf(_, ref expr)
1413 | ast::ExprKind::Box(ref expr)
1414 | ast::ExprKind::Try(ref expr)
1415 | ast::ExprKind::Unary(_, ref expr)
1416 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1421 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1423 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1424 ast::ExprKind::AddrOf(_, ref expr)
1425 | ast::ExprKind::Box(ref expr)
1426 | ast::ExprKind::Try(ref expr)
1427 | ast::ExprKind::Unary(_, ref expr)
1428 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1433 /// Return true if a function call or a method call represented by the given span ends with a
1434 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1435 /// comma from macro can potentially break the code.
1436 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
1437 let mut result: bool = Default::default();
1438 let mut prev_char: char = Default::default();
1440 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1442 _ if kind.is_comment() || c.is_whitespace() => continue,
1443 ')' | '}' => result = result && prev_char != ')' && prev_char != '}',
1444 ',' => result = true,
1445 _ => result = false,
1454 context: &RewriteContext,
1455 mut subexpr: &ast::Expr,
1458 ) -> Option<String> {
1459 debug!("rewrite_paren, shape: {:?}", shape);
1461 // Extract comments within parens.
1462 let mut pre_comment;
1463 let mut post_comment;
1466 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1467 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1468 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1469 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1471 // Remove nested parens if there are no comments.
1472 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1473 if pre_comment.is_empty() && post_comment.is_empty() {
1474 span = subexpr.span;
1475 subexpr = subsubexpr;
1483 let total_paren_overhead = paren_overhead(context);
1484 let paren_overhead = total_paren_overhead / 2;
1485 let sub_shape = shape
1486 .offset_left(paren_overhead)
1487 .and_then(|s| s.sub_width(paren_overhead))?;
1489 let paren_wrapper = |s: &str| {
1490 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
1491 format!("( {}{}{} )", pre_comment, s, post_comment)
1493 format!("({}{}{})", pre_comment, s, post_comment)
1497 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1498 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1500 if subexpr_str.contains('\n')
1501 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
1503 Some(paren_wrapper(&subexpr_str))
1512 context: &RewriteContext,
1514 ) -> Option<String> {
1515 let expr_str = expr.rewrite(context, shape)?;
1517 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
1523 let offset = last_line_width(&expr_str) + lbr.len();
1524 let rhs_overhead = shape.rhs_overhead(context.config);
1525 let index_shape = if expr_str.contains('\n') {
1526 Shape::legacy(context.config.max_width(), shape.indent)
1527 .offset_left(offset)
1528 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
1530 shape.visual_indent(offset).sub_width(offset + rbr.len())
1532 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1534 // Return if index fits in a single line.
1535 match orig_index_rw {
1536 Some(ref index_str) if !index_str.contains('\n') => {
1537 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
1542 // Try putting index on the next line and see if it fits in a single line.
1543 let indent = shape.indent.block_indent(context.config);
1544 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
1545 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
1546 let new_index_rw = index.rewrite(context, index_shape);
1547 match (orig_index_rw, new_index_rw) {
1548 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1551 indent.to_string_with_newline(context.config),
1556 (None, Some(ref new_index_str)) => Some(format!(
1559 indent.to_string_with_newline(context.config),
1564 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
1569 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
1574 fields.iter().all(|field| !field.is_shorthand)
1577 fn rewrite_struct_lit<'a>(
1578 context: &RewriteContext,
1580 fields: &'a [ast::Field],
1581 base: Option<&'a ast::Expr>,
1584 ) -> Option<String> {
1585 debug!("rewrite_struct_lit: shape {:?}", shape);
1587 enum StructLitField<'a> {
1588 Regular(&'a ast::Field),
1589 Base(&'a ast::Expr),
1593 let path_shape = shape.sub_width(2)?;
1594 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1596 if fields.is_empty() && base.is_none() {
1597 return Some(format!("{} {{}}", path_str));
1600 // Foo { a: Foo } - indent is +3, width is -5.
1601 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1603 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1604 let body_lo = context.snippet_provider.span_after(span, "{");
1605 let fields_str = if struct_lit_can_be_aligned(fields, &base)
1606 && context.config.struct_field_align_threshold() > 0
1608 rewrite_with_alignment(
1612 mk_sp(body_lo, span.hi()),
1616 let field_iter = fields
1618 .map(StructLitField::Regular)
1619 .chain(base.into_iter().map(StructLitField::Base));
1621 let span_lo = |item: &StructLitField| match *item {
1622 StructLitField::Regular(field) => field.span().lo(),
1623 StructLitField::Base(expr) => {
1624 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1625 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1626 let pos = snippet.find_uncommented("..").unwrap();
1627 last_field_hi + BytePos(pos as u32)
1630 let span_hi = |item: &StructLitField| match *item {
1631 StructLitField::Regular(field) => field.span().hi(),
1632 StructLitField::Base(expr) => expr.span.hi(),
1634 let rewrite = |item: &StructLitField| match *item {
1635 StructLitField::Regular(field) => {
1636 // The 1 taken from the v_budget is for the comma.
1637 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1639 StructLitField::Base(expr) => {
1641 expr.rewrite(context, v_shape.offset_left(2)?)
1642 .map(|s| format!("..{}", s))
1646 let items = itemize_list(
1647 context.snippet_provider,
1658 let item_vec = items.collect::<Vec<_>>();
1660 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1661 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1663 let ends_with_comma = span_ends_with_comma(context, span);
1664 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1666 let fmt = struct_lit_formatting(
1670 force_no_trailing_comma || base.is_some(),
1673 write_list(&item_vec, &fmt)?
1676 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1677 Some(format!("{} {{{}}}", path_str, fields_str))
1679 // FIXME if context.config.indent_style() == Visual, but we run out
1680 // of space, we should fall back to BlockIndent.
1683 pub fn wrap_struct_field(
1684 context: &RewriteContext,
1687 nested_shape: Shape,
1688 one_line_width: usize,
1690 if context.config.indent_style() == IndentStyle::Block
1691 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
1692 || fields_str.len() > one_line_width)
1696 nested_shape.indent.to_string_with_newline(context.config),
1698 shape.indent.to_string_with_newline(context.config)
1701 // One liner or visual indent.
1702 format!(" {} ", fields_str)
1706 pub fn struct_lit_field_separator(config: &Config) -> &str {
1707 colon_spaces(config.space_before_colon(), config.space_after_colon())
1710 pub fn rewrite_field(
1711 context: &RewriteContext,
1714 prefix_max_width: usize,
1715 ) -> Option<String> {
1716 if contains_skip(&field.attrs) {
1717 return Some(context.snippet(field.span()).to_owned());
1719 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1720 if !attrs_str.is_empty() {
1721 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1723 let name = &field.ident.name.to_string();
1724 if field.is_shorthand {
1725 Some(attrs_str + &name)
1727 let mut separator = String::from(struct_lit_field_separator(context.config));
1728 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
1729 separator.push(' ');
1731 let overhead = name.len() + separator.len();
1732 let expr_shape = shape.offset_left(overhead)?;
1733 let expr = field.expr.rewrite(context, expr_shape);
1736 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1737 Some(attrs_str + &name)
1739 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1741 let expr_offset = shape.indent.block_indent(context.config);
1744 .rewrite(context, Shape::indented(expr_offset, context.config));
1750 expr_offset.to_string(context.config),
1759 fn rewrite_tuple_in_visual_indent_style<'a, T>(
1760 context: &RewriteContext,
1766 T: Rewrite + Spanned + ToExpr + 'a,
1768 let mut items = items.iter();
1769 // In case of length 1, need a trailing comma
1770 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1771 if items.len() == 1 {
1773 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1777 .rewrite(context, nested_shape)
1779 if context.config.spaces_within_parens_and_brackets() {
1780 format!("( {}, )", s)
1787 let list_lo = context.snippet_provider.span_after(span, "(");
1788 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1789 let items = itemize_list(
1790 context.snippet_provider,
1794 |item| item.span().lo(),
1795 |item| item.span().hi(),
1796 |item| item.rewrite(context, nested_shape),
1798 span.hi() - BytePos(1),
1801 let item_vec: Vec<_> = items.collect();
1802 let tactic = definitive_tactic(
1804 ListTactic::HorizontalVertical,
1808 let fmt = ListFormatting {
1811 trailing_separator: SeparatorTactic::Never,
1812 separator_place: SeparatorPlace::Back,
1814 ends_with_newline: false,
1815 preserve_newline: false,
1816 config: context.config,
1818 let list_str = write_list(&item_vec, &fmt)?;
1820 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
1821 Some(format!("( {} )", list_str))
1823 Some(format!("({})", list_str))
1827 pub fn rewrite_tuple<'a, T>(
1828 context: &RewriteContext,
1834 T: Rewrite + Spanned + ToExpr + 'a,
1836 debug!("rewrite_tuple {:?}", shape);
1837 if context.use_block_indent() {
1838 // We use the same rule as function calls for rewriting tuples.
1839 let force_tactic = if context.inside_macro() {
1840 if span_ends_with_comma(context, span) {
1841 Some(SeparatorTactic::Always)
1843 Some(SeparatorTactic::Never)
1845 } else if items.len() == 1 {
1846 Some(SeparatorTactic::Always)
1850 overflow::rewrite_with_parens(
1856 context.config.width_heuristics().fn_call_width,
1860 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
1864 pub fn rewrite_unary_prefix<R: Rewrite>(
1865 context: &RewriteContext,
1869 ) -> Option<String> {
1871 .rewrite(context, shape.offset_left(prefix.len())?)
1872 .map(|r| format!("{}{}", prefix, r))
1875 // FIXME: this is probably not correct for multi-line Rewrites. we should
1876 // subtract suffix.len() from the last line budget, not the first!
1877 pub fn rewrite_unary_suffix<R: Rewrite>(
1878 context: &RewriteContext,
1882 ) -> Option<String> {
1884 .rewrite(context, shape.sub_width(suffix.len())?)
1891 fn rewrite_unary_op(
1892 context: &RewriteContext,
1896 ) -> Option<String> {
1897 // For some reason, an UnOp is not spanned like BinOp!
1898 let operator_str = match *op {
1899 ast::UnOp::Deref => "*",
1900 ast::UnOp::Not => "!",
1901 ast::UnOp::Neg => "-",
1903 rewrite_unary_prefix(context, operator_str, expr, shape)
1906 fn rewrite_assignment(
1907 context: &RewriteContext,
1910 op: Option<&ast::BinOp>,
1912 ) -> Option<String> {
1913 let operator_str = match op {
1914 Some(op) => context.snippet(op.span),
1918 // 1 = space between lhs and operator.
1919 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1920 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1922 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1925 /// Controls where to put the rhs.
1926 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1927 pub enum RhsTactics {
1930 /// Put the rhs on the next line if it uses multiple line.
1934 // The left hand side must contain everything up to, and including, the
1935 // assignment operator.
1936 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1937 context: &RewriteContext,
1941 ) -> Option<String> {
1942 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1945 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1946 context: &RewriteContext,
1950 rhs_tactics: RhsTactics,
1951 ) -> Option<String> {
1952 let lhs = lhs.into();
1953 let last_line_width = last_line_width(&lhs)
1954 .checked_sub(if lhs.contains('\n') {
1955 shape.indent.width()
1960 // 1 = space between operator and rhs.
1961 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1963 offset: shape.offset + last_line_width + 1,
1966 let rhs = choose_rhs(
1970 ex.rewrite(context, orig_shape),
1976 fn choose_rhs<R: Rewrite>(
1977 context: &RewriteContext,
1980 orig_rhs: Option<String>,
1981 rhs_tactics: RhsTactics,
1982 ) -> Option<String> {
1984 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1985 Some(format!(" {}", new_str))
1988 // Expression did not fit on the same line as the identifier.
1989 // Try splitting the line and see if that works better.
1991 Shape::indented(shape.indent.block_indent(context.config), context.config)
1992 .sub_width(shape.rhs_overhead(context.config))?;
1993 let new_rhs = expr.rewrite(context, new_shape);
1994 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
1996 match (orig_rhs, new_rhs) {
1997 (Some(ref orig_rhs), Some(ref new_rhs))
1998 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2001 Some(format!(" {}", orig_rhs))
2003 (Some(ref orig_rhs), Some(ref new_rhs))
2004 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2006 Some(format!("{}{}", new_indent_str, new_rhs))
2008 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2009 (None, None) => None,
2010 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2016 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
2017 rhs_tactics == RhsTactics::ForceNextLine || !next_line_rhs.contains('\n')
2018 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2021 fn rewrite_expr_addrof(
2022 context: &RewriteContext,
2023 mutability: ast::Mutability,
2026 ) -> Option<String> {
2027 let operator_str = match mutability {
2028 ast::Mutability::Immutable => "&",
2029 ast::Mutability::Mutable => "&mut ",
2031 rewrite_unary_prefix(context, operator_str, expr, shape)
2035 fn to_expr(&self) -> Option<&ast::Expr>;
2036 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2039 impl ToExpr for ast::Expr {
2040 fn to_expr(&self) -> Option<&ast::Expr> {
2044 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2045 can_be_overflowed_expr(context, self, len)
2049 impl ToExpr for ast::Ty {
2050 fn to_expr(&self) -> Option<&ast::Expr> {
2054 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2055 can_be_overflowed_type(context, self, len)
2059 impl<'a> ToExpr for TuplePatField<'a> {
2060 fn to_expr(&self) -> Option<&ast::Expr> {
2064 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2065 can_be_overflowed_pat(context, self, len)
2069 impl<'a> ToExpr for ast::StructField {
2070 fn to_expr(&self) -> Option<&ast::Expr> {
2074 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2079 impl<'a> ToExpr for MacroArg {
2080 fn to_expr(&self) -> Option<&ast::Expr> {
2082 MacroArg::Expr(ref expr) => Some(expr),
2087 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2089 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2090 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2091 MacroArg::Pat(..) => false,
2092 MacroArg::Item(..) => len == 1,
2097 impl ToExpr for ast::GenericParam {
2098 fn to_expr(&self) -> Option<&ast::Expr> {
2102 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {