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::parse::token::DelimToken;
16 use syntax::source_map::{BytePos, SourceMap, Span};
17 use syntax::{ast, ptr};
19 use chains::rewrite_chain;
22 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
23 rewrite_missing_comment, CharClasses, FindUncommented,
25 use config::{Config, ControlBraceStyle, IndentStyle};
27 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
28 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
30 use macros::{rewrite_macro, MacroArg, MacroPosition};
31 use matches::rewrite_match;
33 use pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
34 use patterns::{can_be_overflowed_pat, is_short_pattern, TuplePatField};
35 use rewrite::{Rewrite, RewriteContext};
36 use shape::{Indent, Shape};
37 use source_map::{LineRangeUtils, SpanUtils};
39 use string::{rewrite_string, StringFormat};
40 use types::{can_be_overflowed_type, rewrite_path, PathContext};
42 colon_spaces, contains_skip, count_newlines, first_line_ends_with, first_line_width,
43 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
44 ptr_vec_to_ref_vec, semicolon_for_stmt, wrap_str,
46 use vertical::rewrite_with_alignment;
47 use visitor::FmtVisitor;
49 impl Rewrite for ast::Expr {
50 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
51 format_expr(self, ExprType::SubExpression, context, shape)
55 #[derive(Copy, Clone, PartialEq)]
64 context: &RewriteContext,
67 skip_out_of_file_lines_range!(context, expr.span);
69 if contains_skip(&*expr.attrs) {
70 return Some(context.snippet(expr.span()).to_owned());
73 let expr_rw = match expr.node {
74 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
76 &ptr_vec_to_ref_vec(expr_vec),
80 choose_separator_tactic(context, expr.span),
83 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
84 ast::ExprKind::Call(ref callee, ref args) => {
85 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
86 let callee_str = callee.rewrite(context, shape)?;
87 rewrite_call(context, &callee_str, args, inner_span, shape)
89 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
90 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
91 // FIXME: format comments between operands and operator
92 rewrite_all_pairs(expr, shape, context).or_else(|| {
96 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
99 context.config.binop_separator(),
103 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
104 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
108 base.as_ref().map(|e| &**e),
112 ast::ExprKind::Tup(ref items) => {
113 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
115 ast::ExprKind::If(..)
116 | ast::ExprKind::IfLet(..)
117 | ast::ExprKind::ForLoop(..)
118 | ast::ExprKind::Loop(..)
119 | ast::ExprKind::While(..)
120 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
121 .and_then(|control_flow| control_flow.rewrite(context, shape)),
122 ast::ExprKind::Block(ref block, opt_label) => {
124 ExprType::Statement => {
125 if is_unsafe_block(block) {
126 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
127 } else if let rw @ Some(_) =
128 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
130 // Rewrite block without trying to put it in a single line.
133 let prefix = block_prefix(context, block, shape)?;
135 rewrite_block_with_visitor(
146 ExprType::SubExpression => {
147 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
151 ast::ExprKind::Match(ref cond, ref arms) => {
152 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
154 ast::ExprKind::Path(ref qself, ref path) => {
155 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
157 ast::ExprKind::Assign(ref lhs, ref rhs) => {
158 rewrite_assignment(context, lhs, rhs, None, shape)
160 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
161 rewrite_assignment(context, lhs, rhs, Some(op), shape)
163 ast::ExprKind::Continue(ref opt_label) => {
164 let id_str = match *opt_label {
165 Some(label) => format!(" {}", label.ident),
166 None => String::new(),
168 Some(format!("continue{}", id_str))
170 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
171 let id_str = match *opt_label {
172 Some(label) => format!(" {}", label.ident),
173 None => String::new(),
176 if let Some(ref expr) = *opt_expr {
177 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
179 Some(format!("break{}", id_str))
182 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
183 rewrite_unary_prefix(context, "yield ", &**expr, shape)
185 Some("yield".to_string())
187 ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) => {
188 closures::rewrite_closure(
189 capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
192 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
193 rewrite_chain(expr, context, shape)
195 ast::ExprKind::Mac(ref mac) => {
196 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
198 context.snippet(expr.span).to_owned(),
199 context.config.max_width(),
204 ast::ExprKind::Ret(None) => Some("return".to_owned()),
205 ast::ExprKind::Ret(Some(ref expr)) => {
206 rewrite_unary_prefix(context, "return ", &**expr, shape)
208 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
209 ast::ExprKind::AddrOf(mutability, ref expr) => {
210 rewrite_expr_addrof(context, mutability, expr, shape)
212 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
215 PairParts::infix(" as "),
218 SeparatorPlace::Front,
220 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
223 PairParts::infix(": "),
226 SeparatorPlace::Back,
228 ast::ExprKind::Index(ref expr, ref index) => {
229 rewrite_index(&**expr, &**index, context, shape)
231 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
234 PairParts::new("[", "; ", "]"),
237 SeparatorPlace::Back,
239 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
240 let delim = match limits {
241 ast::RangeLimits::HalfOpen => "..",
242 ast::RangeLimits::Closed => "..=",
245 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
247 ast::ExprKind::Lit(ref lit) => match lit.node {
248 ast::LitKind::FloatUnsuffixed(..) => {
249 context.snippet(lit.span).ends_with('.')
257 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
259 // Don't format `.. ..` into `....`, which is invalid.
261 // This check is unnecessary for `lhs`, because a range
262 // starting from another range needs parentheses as `(x ..) ..`
263 // (`x .. ..` is a range from `x` to `..`).
264 ast::ExprKind::Range(None, _, _) => true,
269 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
270 let space_if = |b: bool| if b { " " } else { "" };
274 lhs.map(|lhs| space_if(needs_space_before_range(context, lhs)))
277 rhs.map(|rhs| space_if(needs_space_after_range(rhs)))
282 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
283 (Some(lhs), Some(rhs)) => {
284 let sp_delim = if context.config.spaces_around_ranges() {
285 format!(" {} ", delim)
287 default_sp_delim(Some(lhs), Some(rhs))
292 PairParts::infix(&sp_delim),
295 context.config.binop_separator(),
298 (None, Some(rhs)) => {
299 let sp_delim = if context.config.spaces_around_ranges() {
300 format!("{} ", delim)
302 default_sp_delim(None, Some(rhs))
304 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
306 (Some(lhs), None) => {
307 let sp_delim = if context.config.spaces_around_ranges() {
308 format!(" {}", delim)
310 default_sp_delim(Some(lhs), None)
312 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
314 (None, None) => Some(delim.to_owned()),
317 // We do not format these expressions yet, but they should still
318 // satisfy our width restrictions.
319 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
320 ast::ExprKind::TryBlock(ref block) => {
321 if let rw @ Some(_) =
322 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
327 let budget = shape.width.saturating_sub(9);
336 Shape::legacy(budget, shape.indent)
342 ast::ExprKind::ObsoleteInPlace(..) => unimplemented!(),
343 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
344 let mover = if capture_by == ast::CaptureBy::Value {
349 if let rw @ Some(_) = rewrite_single_line_block(
351 format!("{}{}", "async ", mover).as_str(),
360 let budget = shape.width.saturating_sub(6);
370 Shape::legacy(budget, shape.indent)
378 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
379 .and_then(|expr_str| {
380 let attrs = outer_attributes(&expr.attrs);
381 let attrs_str = attrs.rewrite(context, shape)?;
383 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
386 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
390 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
394 context: &RewriteContext,
396 force_separator_tactic: Option<SeparatorTactic>,
397 delim_token: Option<DelimToken>,
398 ) -> Option<String> {
399 overflow::rewrite_with_square_brackets(
405 force_separator_tactic,
410 fn rewrite_empty_block(
411 context: &RewriteContext,
413 attrs: Option<&[ast::Attribute]>,
414 label: Option<ast::Label>,
417 ) -> Option<String> {
418 let label_str = rewrite_label(label);
419 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
423 if block.stmts.is_empty()
424 && !block_contains_comment(block, context.source_map)
427 return Some(format!("{}{}{{}}", prefix, label_str));
430 // If a block contains only a single-line comment, then leave it on one line.
431 let user_str = context.snippet(block.span);
432 let user_str = user_str.trim();
433 if user_str.starts_with('{') && user_str.ends_with('}') {
434 let comment_str = user_str[1..user_str.len() - 1].trim();
435 if block.stmts.is_empty()
436 && !comment_str.contains('\n')
437 && !comment_str.starts_with("//")
438 && comment_str.len() + 4 <= shape.width
440 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
447 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
448 Some(match block.rules {
449 ast::BlockCheckMode::Unsafe(..) => {
450 let snippet = context.snippet(block.span);
451 let open_pos = snippet.find_uncommented("{")?;
452 // Extract comment between unsafe and block start.
453 let trimmed = &snippet[6..open_pos].trim();
455 if !trimmed.is_empty() {
456 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
457 let budget = shape.width.checked_sub(9)?;
463 Shape::legacy(budget, shape.indent + 7),
471 ast::BlockCheckMode::Default => String::new(),
475 fn rewrite_single_line_block(
476 context: &RewriteContext,
479 attrs: Option<&[ast::Attribute]>,
480 label: Option<ast::Label>,
482 ) -> Option<String> {
483 if is_simple_block(block, attrs, context.source_map) {
484 let expr_shape = shape.offset_left(last_line_width(prefix))?;
485 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
486 let label_str = rewrite_label(label);
487 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
488 if result.len() <= shape.width && !result.contains('\n') {
495 pub fn rewrite_block_with_visitor(
496 context: &RewriteContext,
499 attrs: Option<&[ast::Attribute]>,
500 label: Option<ast::Label>,
503 ) -> Option<String> {
504 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
508 let mut visitor = FmtVisitor::from_context(context);
509 visitor.block_indent = shape.indent;
510 visitor.is_if_else_block = context.is_if_else_block();
512 ast::BlockCheckMode::Unsafe(..) => {
513 let snippet = context.snippet(block.span);
514 let open_pos = snippet.find_uncommented("{")?;
515 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
517 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
520 let inner_attrs = attrs.map(inner_attributes);
521 let label_str = rewrite_label(label);
522 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
523 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
526 impl Rewrite for ast::Block {
527 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
528 rewrite_block(self, None, None, context, shape)
534 attrs: Option<&[ast::Attribute]>,
535 label: Option<ast::Label>,
536 context: &RewriteContext,
538 ) -> Option<String> {
539 let prefix = block_prefix(context, block, shape)?;
541 // shape.width is used only for the single line case: either the empty block `{}`,
542 // or an unsafe expression `unsafe { e }`.
543 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
547 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
548 if let Some(ref result_str) = result {
549 if result_str.lines().count() <= 3 {
550 if let rw @ Some(_) =
551 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
561 impl Rewrite for ast::Stmt {
562 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
563 skip_out_of_file_lines_range!(context, self.span());
565 let result = match self.node {
566 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
567 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
568 let suffix = if semicolon_for_stmt(context, self) {
574 let shape = shape.sub_width(suffix.len())?;
575 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
577 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
579 result.and_then(|res| recover_comment_removed(res, self.span(), context))
583 // Rewrite condition if the given expression has one.
584 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
586 ast::ExprKind::Match(ref cond, _) => {
588 let cond_shape = match context.config.indent_style() {
589 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
590 IndentStyle::Block => shape.offset_left(8)?,
592 cond.rewrite(context, cond_shape)
594 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
596 String::from("\n") + &shape.indent.block_only().to_string(context.config);
598 .rewrite_cond(context, shape, &alt_block_sep)
599 .and_then(|rw| Some(rw.0))
604 // Abstraction over control flow expressions
606 struct ControlFlow<'a> {
607 cond: Option<&'a ast::Expr>,
608 block: &'a ast::Block,
609 else_block: Option<&'a ast::Expr>,
610 label: Option<ast::Label>,
611 pats: Vec<&'a ast::Pat>,
615 allow_single_line: bool,
616 // True if this is an `if` expression in an `else if` :-( hacky
621 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
623 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
627 else_block.as_ref().map(|e| &**e),
628 expr_type == ExprType::SubExpression,
632 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
633 Some(ControlFlow::new_if(
635 ptr_vec_to_ref_vec(pat),
637 else_block.as_ref().map(|e| &**e),
638 expr_type == ExprType::SubExpression,
643 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
644 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
646 ast::ExprKind::Loop(ref block, label) => {
647 Some(ControlFlow::new_loop(block, label, expr.span))
649 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
656 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
657 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
663 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
671 impl<'a> ControlFlow<'a> {
674 pats: Vec<&'a ast::Pat>,
675 block: &'a ast::Block,
676 else_block: Option<&'a ast::Expr>,
677 allow_single_line: bool,
680 ) -> ControlFlow<'a> {
681 let matcher = choose_matcher(&pats);
697 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
707 allow_single_line: false,
714 pats: Vec<&'a ast::Pat>,
716 block: &'a ast::Block,
717 label: Option<ast::Label>,
719 ) -> ControlFlow<'a> {
720 let matcher = choose_matcher(&pats);
730 allow_single_line: false,
739 block: &'a ast::Block,
740 label: Option<ast::Label>,
742 ) -> ControlFlow<'a> {
752 allow_single_line: false,
758 fn rewrite_single_line(
761 context: &RewriteContext,
763 ) -> Option<String> {
764 assert!(self.allow_single_line);
765 let else_block = self.else_block?;
766 let fixed_cost = self.keyword.len() + " { } else { }".len();
768 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
769 if !is_simple_block(self.block, None, context.source_map)
770 || !is_simple_block(else_node, None, context.source_map)
771 || pat_expr_str.contains('\n')
776 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
777 let expr = &self.block.stmts[0];
778 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
780 let new_width = new_width.checked_sub(if_str.len())?;
781 let else_expr = &else_node.stmts[0];
782 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
784 if if_str.contains('\n') || else_str.contains('\n') {
788 let result = format!(
789 "{} {} {{ {} }} else {{ {} }}",
790 self.keyword, pat_expr_str, if_str, else_str
793 if result.len() <= width {
802 impl<'a> ControlFlow<'a> {
805 context: &RewriteContext,
809 ) -> Option<String> {
810 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
812 let cond_shape = shape.offset_left(offset)?;
813 if !self.pats.is_empty() {
814 let matcher = if self.matcher.is_empty() {
815 self.matcher.to_owned()
817 format!("{} ", self.matcher)
819 let pat_shape = cond_shape
820 .offset_left(matcher.len())?
821 .sub_width(self.connector.len())?;
822 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
823 let result = format!("{}{}{}", matcher, pat_string, self.connector);
824 return rewrite_assign_rhs(context, result, expr, cond_shape);
827 let expr_rw = expr.rewrite(context, cond_shape);
828 // The expression may (partially) fit on the current line.
829 // We do not allow splitting between `if` and condition.
830 if self.keyword == "if" || expr_rw.is_some() {
834 // The expression won't fit on the current line, jump to next.
835 let nested_shape = shape
836 .block_indent(context.config.tab_spaces())
837 .with_max_width(context.config);
838 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
839 expr.rewrite(context, nested_shape)
840 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
845 context: &RewriteContext,
848 ) -> Option<(String, usize)> {
849 // Do not take the rhs overhead from the upper expressions into account
850 // when rewriting pattern.
851 let new_width = context.budget(shape.used_width());
852 let fresh_shape = Shape {
856 let constr_shape = if self.nested_if {
857 // We are part of an if-elseif-else chain. Our constraints are tightened.
858 // 7 = "} else " .len()
859 fresh_shape.offset_left(7)?
864 let label_string = rewrite_label(self.label);
865 // 1 = space after keyword.
866 let offset = self.keyword.len() + label_string.len() + 1;
868 let pat_expr_string = match self.cond {
869 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
870 None => String::new(),
874 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
880 let one_line_budget = context
883 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
884 let force_newline_brace = (pat_expr_string.contains('\n')
885 || pat_expr_string.len() > one_line_budget)
886 && !last_line_extendable(&pat_expr_string);
888 // Try to format if-else on single line.
889 if self.allow_single_line
893 .single_line_if_else_max_width
896 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
898 if let Some(cond_str) = trial {
899 if cond_str.len() <= context
902 .single_line_if_else_max_width
904 return Some((cond_str, 0));
909 let cond_span = if let Some(cond) = self.cond {
912 mk_sp(self.block.span.lo(), self.block.span.lo())
915 // `for event in event`
916 // Do not include label in the span.
919 .map_or(self.span.lo(), |label| label.ident.span.hi());
920 let between_kwd_cond = mk_sp(
923 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
924 if self.pats.is_empty() {
926 } else if self.matcher.is_empty() {
927 self.pats[0].span.lo()
931 .span_before(self.span, self.matcher.trim())
935 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
937 let after_cond_comment =
938 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
940 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
942 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
943 || force_newline_brace
950 let used_width = if pat_expr_string.contains('\n') {
951 last_line_width(&pat_expr_string)
953 // 2 = spaces after keyword and condition.
954 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
962 between_kwd_cond_comment.as_ref().map_or(
963 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
971 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
978 impl<'a> Rewrite for ControlFlow<'a> {
979 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
980 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
982 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
983 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
984 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
986 return Some(cond_str);
989 let block_width = shape.width.saturating_sub(used_width);
990 // This is used only for the empty block case: `{}`. So, we use 1 if we know
991 // we should avoid the single line case.
992 let block_width = if self.else_block.is_some() || self.nested_if {
997 let block_shape = Shape {
1002 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1004 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1005 context.is_if_else_block.replace(old_val);
1009 let mut result = format!("{}{}", cond_str, block_str);
1011 if let Some(else_block) = self.else_block {
1012 let shape = Shape::indented(shape.indent, context.config);
1013 let mut last_in_chain = false;
1014 let rewrite = match else_block.node {
1015 // If the else expression is another if-else expression, prevent it
1016 // from being formatted on a single line.
1017 // Note how we're passing the original shape, as the
1018 // cost of "else" should not cascade.
1019 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1020 ControlFlow::new_if(
1022 ptr_vec_to_ref_vec(pat),
1024 next_else_block.as_ref().map(|e| &**e),
1027 mk_sp(else_block.span.lo(), self.span.hi()),
1028 ).rewrite(context, shape)
1030 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1031 ControlFlow::new_if(
1035 next_else_block.as_ref().map(|e| &**e),
1038 mk_sp(else_block.span.lo(), self.span.hi()),
1039 ).rewrite(context, shape)
1042 last_in_chain = true;
1043 // When rewriting a block, the width is only used for single line
1044 // blocks, passing 1 lets us avoid that.
1045 let else_shape = Shape {
1046 width: min(1, shape.width),
1049 format_expr(else_block, ExprType::Statement, context, else_shape)
1053 let between_kwd_else_block = mk_sp(
1054 self.block.span.hi(),
1057 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1059 let between_kwd_else_block_comment =
1060 extract_comment(between_kwd_else_block, context, shape);
1062 let after_else = mk_sp(
1065 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1066 else_block.span.lo(),
1068 let after_else_comment = extract_comment(after_else, context, shape);
1070 let between_sep = match context.config.control_brace_style() {
1071 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1074 ControlBraceStyle::AlwaysSameLine => " ",
1076 let after_sep = match context.config.control_brace_style() {
1077 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1081 result.push_str(&format!(
1083 between_kwd_else_block_comment
1085 .map_or(between_sep, |s| &**s),
1086 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1088 result.push_str(&rewrite?);
1095 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1097 Some(label) => Cow::from(format!("{}: ", label.ident)),
1098 None => Cow::from(""),
1102 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1103 match rewrite_missing_comment(span, shape, context) {
1104 Some(ref comment) if !comment.is_empty() => Some(format!(
1105 "{indent}{}{indent}",
1107 indent = shape.indent.to_string_with_newline(context.config)
1113 pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1114 let snippet = source_map.span_to_snippet(block.span).unwrap();
1115 contains_comment(&snippet)
1118 // Checks that a block contains no statements, an expression and no comments or
1120 // FIXME: incorrectly returns false when comment is contained completely within
1122 pub fn is_simple_block(
1124 attrs: Option<&[ast::Attribute]>,
1125 source_map: &SourceMap,
1127 (block.stmts.len() == 1
1128 && stmt_is_expr(&block.stmts[0])
1129 && !block_contains_comment(block, source_map)
1130 && attrs.map_or(true, |a| a.is_empty()))
1133 /// Checks whether a block contains at most one statement or expression, and no
1134 /// comments or attributes.
1135 pub fn is_simple_block_stmt(
1137 attrs: Option<&[ast::Attribute]>,
1138 source_map: &SourceMap,
1140 block.stmts.len() <= 1
1141 && !block_contains_comment(block, source_map)
1142 && attrs.map_or(true, |a| a.is_empty())
1145 /// Checks whether a block contains no statements, expressions, comments, or
1146 /// inner attributes.
1147 pub fn is_empty_block(
1149 attrs: Option<&[ast::Attribute]>,
1150 source_map: &SourceMap,
1152 block.stmts.is_empty()
1153 && !block_contains_comment(block, source_map)
1154 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1157 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1159 ast::StmtKind::Expr(..) => true,
1164 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1165 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1172 pub fn rewrite_multiple_patterns(
1173 context: &RewriteContext,
1176 ) -> Option<String> {
1179 .map(|p| p.rewrite(context, shape))
1180 .collect::<Option<Vec<_>>>()?;
1182 let use_mixed_layout = pats
1184 .zip(pat_strs.iter())
1185 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1186 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1187 let tactic = if use_mixed_layout {
1188 DefinitiveListTactic::Mixed
1192 ListTactic::HorizontalVertical,
1193 Separator::VerticalBar,
1197 let fmt = ListFormatting::new(shape, context.config)
1200 .separator_place(context.config.binop_separator())
1201 .ends_with_newline(false);
1202 write_list(&items, &fmt)
1205 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1207 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1209 context.snippet(l.span).to_owned(),
1210 context.config.max_width(),
1216 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1217 let string_lit = context.snippet(span);
1219 if !context.config.format_strings() {
1224 .all(|line| line.ends_with('\\'))
1226 let new_indent = shape.visual_indent(1).indent;
1227 let indented_string_lit = String::from(
1233 new_indent.to_string(context.config),
1236 }).collect::<Vec<_>>()
1240 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1242 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1246 // Remove the quote characters.
1247 let str_lit = &string_lit[1..string_lit.len() - 1];
1251 &StringFormat::new(shape.visual_indent(0), context.config),
1255 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1256 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1257 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1259 .find(|&&(s, _)| s == callee_str)
1261 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1263 Some((all_simple, num_args_before))
1269 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1272 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1273 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1274 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1275 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1276 // format! like macros
1277 // From the Rust Standard Library.
1281 ("format_args!", 0),
1285 ("unreachable!", 0),
1286 // From the `log` crate.
1291 // write! like macros
1293 ("debug_assert!", 1),
1296 // assert_eq! like macros
1299 ("debug_assert_eq!", 2),
1300 ("debug_assert_ne!", 2),
1303 fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<SeparatorTactic> {
1304 if context.inside_macro() {
1305 if span_ends_with_comma(context, span) {
1306 Some(SeparatorTactic::Always)
1308 Some(SeparatorTactic::Never)
1315 pub fn rewrite_call(
1316 context: &RewriteContext,
1318 args: &[ptr::P<ast::Expr>],
1321 ) -> Option<String> {
1322 overflow::rewrite_with_parens(
1325 &ptr_vec_to_ref_vec(args),
1328 context.config.width_heuristics().fn_call_width,
1329 choose_separator_tactic(context, span),
1333 fn is_simple_expr(expr: &ast::Expr) -> bool {
1335 ast::ExprKind::Lit(..) => true,
1336 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1337 ast::ExprKind::AddrOf(_, ref expr)
1338 | ast::ExprKind::Box(ref expr)
1339 | ast::ExprKind::Cast(ref expr, _)
1340 | ast::ExprKind::Field(ref expr, _)
1341 | ast::ExprKind::Try(ref expr)
1342 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1343 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1344 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1345 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1351 pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1354 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1357 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1359 ast::ExprKind::Match(..) => {
1360 (context.use_block_indent() && args_len == 1)
1361 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1363 ast::ExprKind::If(..)
1364 | ast::ExprKind::IfLet(..)
1365 | ast::ExprKind::ForLoop(..)
1366 | ast::ExprKind::Loop(..)
1367 | ast::ExprKind::While(..)
1368 | ast::ExprKind::WhileLet(..) => {
1369 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1371 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1372 context.use_block_indent()
1373 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1375 ast::ExprKind::Array(..)
1376 | ast::ExprKind::Call(..)
1377 | ast::ExprKind::Mac(..)
1378 | ast::ExprKind::MethodCall(..)
1379 | ast::ExprKind::Struct(..)
1380 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1381 ast::ExprKind::AddrOf(_, ref expr)
1382 | ast::ExprKind::Box(ref expr)
1383 | ast::ExprKind::Try(ref expr)
1384 | ast::ExprKind::Unary(_, ref expr)
1385 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1390 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1392 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1393 ast::ExprKind::AddrOf(_, ref expr)
1394 | ast::ExprKind::Box(ref expr)
1395 | ast::ExprKind::Try(ref expr)
1396 | ast::ExprKind::Unary(_, ref expr)
1397 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1402 /// Return true if a function call or a method call represented by the given span ends with a
1403 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1404 /// comma from macro can potentially break the code.
1405 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
1406 let mut result: bool = Default::default();
1407 let mut prev_char: char = Default::default();
1408 let closing_delimiters = &[')', '}', ']'];
1410 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1412 _ if kind.is_comment() || c.is_whitespace() => continue,
1413 c if closing_delimiters.contains(&c) => {
1414 result &= !closing_delimiters.contains(&prev_char);
1416 ',' => result = true,
1417 _ => result = false,
1426 context: &RewriteContext,
1427 mut subexpr: &ast::Expr,
1430 ) -> Option<String> {
1431 debug!("rewrite_paren, shape: {:?}", shape);
1433 // Extract comments within parens.
1434 let mut pre_comment;
1435 let mut post_comment;
1436 let remove_nested_parens = context.config.remove_nested_parens();
1439 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1440 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1441 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1442 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1444 // Remove nested parens if there are no comments.
1445 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1446 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1447 span = subexpr.span;
1448 subexpr = subsubexpr;
1457 let sub_shape = shape.offset_left(1).and_then(|s| s.sub_width(1))?;
1459 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1460 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1463 if subexpr_str.contains('\n') || first_line_width(&subexpr_str) + 2 <= shape.width {
1464 Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
1473 context: &RewriteContext,
1475 ) -> Option<String> {
1476 let expr_str = expr.rewrite(context, shape)?;
1478 let offset = last_line_width(&expr_str) + 1;
1479 let rhs_overhead = shape.rhs_overhead(context.config);
1480 let index_shape = if expr_str.contains('\n') {
1481 Shape::legacy(context.config.max_width(), shape.indent)
1482 .offset_left(offset)
1483 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1485 shape.visual_indent(offset).sub_width(offset + 1)
1487 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1489 // Return if index fits in a single line.
1490 match orig_index_rw {
1491 Some(ref index_str) if !index_str.contains('\n') => {
1492 return Some(format!("{}[{}]", expr_str, index_str));
1497 // Try putting index on the next line and see if it fits in a single line.
1498 let indent = shape.indent.block_indent(context.config);
1499 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1500 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1501 let new_index_rw = index.rewrite(context, index_shape);
1502 match (orig_index_rw, new_index_rw) {
1503 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1506 indent.to_string_with_newline(context.config),
1509 (None, Some(ref new_index_str)) => Some(format!(
1512 indent.to_string_with_newline(context.config),
1515 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1520 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
1525 fields.iter().all(|field| !field.is_shorthand)
1528 fn rewrite_struct_lit<'a>(
1529 context: &RewriteContext,
1531 fields: &'a [ast::Field],
1532 base: Option<&'a ast::Expr>,
1535 ) -> Option<String> {
1536 debug!("rewrite_struct_lit: shape {:?}", shape);
1538 enum StructLitField<'a> {
1539 Regular(&'a ast::Field),
1540 Base(&'a ast::Expr),
1544 let path_shape = shape.sub_width(2)?;
1545 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1547 if fields.is_empty() && base.is_none() {
1548 return Some(format!("{} {{}}", path_str));
1551 // Foo { a: Foo } - indent is +3, width is -5.
1552 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1554 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1555 let body_lo = context.snippet_provider.span_after(span, "{");
1556 let fields_str = if struct_lit_can_be_aligned(fields, &base)
1557 && context.config.struct_field_align_threshold() > 0
1559 rewrite_with_alignment(
1563 mk_sp(body_lo, span.hi()),
1567 let field_iter = fields
1569 .map(StructLitField::Regular)
1570 .chain(base.into_iter().map(StructLitField::Base));
1572 let span_lo = |item: &StructLitField| match *item {
1573 StructLitField::Regular(field) => field.span().lo(),
1574 StructLitField::Base(expr) => {
1575 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1576 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1577 let pos = snippet.find_uncommented("..").unwrap();
1578 last_field_hi + BytePos(pos as u32)
1581 let span_hi = |item: &StructLitField| match *item {
1582 StructLitField::Regular(field) => field.span().hi(),
1583 StructLitField::Base(expr) => expr.span.hi(),
1585 let rewrite = |item: &StructLitField| match *item {
1586 StructLitField::Regular(field) => {
1587 // The 1 taken from the v_budget is for the comma.
1588 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1590 StructLitField::Base(expr) => {
1592 expr.rewrite(context, v_shape.offset_left(2)?)
1593 .map(|s| format!("..{}", s))
1597 let items = itemize_list(
1598 context.snippet_provider,
1609 let item_vec = items.collect::<Vec<_>>();
1611 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1612 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1614 let ends_with_comma = span_ends_with_comma(context, span);
1615 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1617 let fmt = struct_lit_formatting(
1621 force_no_trailing_comma || base.is_some(),
1624 write_list(&item_vec, &fmt)?
1627 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1628 Some(format!("{} {{{}}}", path_str, fields_str))
1630 // FIXME if context.config.indent_style() == Visual, but we run out
1631 // of space, we should fall back to BlockIndent.
1634 pub fn wrap_struct_field(
1635 context: &RewriteContext,
1638 nested_shape: Shape,
1639 one_line_width: usize,
1641 if context.config.indent_style() == IndentStyle::Block
1642 && (fields_str.contains('\n')
1643 || !context.config.struct_lit_single_line()
1644 || fields_str.len() > one_line_width)
1648 nested_shape.indent.to_string_with_newline(context.config),
1650 shape.indent.to_string_with_newline(context.config)
1653 // One liner or visual indent.
1654 format!(" {} ", fields_str)
1658 pub fn struct_lit_field_separator(config: &Config) -> &str {
1659 colon_spaces(config.space_before_colon(), config.space_after_colon())
1662 pub fn rewrite_field(
1663 context: &RewriteContext,
1666 prefix_max_width: usize,
1667 ) -> Option<String> {
1668 if contains_skip(&field.attrs) {
1669 return Some(context.snippet(field.span()).to_owned());
1671 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1672 if !attrs_str.is_empty() {
1673 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1675 let name = context.snippet(field.ident.span);
1676 if field.is_shorthand {
1677 Some(attrs_str + &name)
1679 let mut separator = String::from(struct_lit_field_separator(context.config));
1680 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1681 separator.push(' ');
1683 let overhead = name.len() + separator.len();
1684 let expr_shape = shape.offset_left(overhead)?;
1685 let expr = field.expr.rewrite(context, expr_shape);
1688 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1689 Some(attrs_str + &name)
1691 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1693 let expr_offset = shape.indent.block_indent(context.config);
1696 .rewrite(context, Shape::indented(expr_offset, context.config));
1702 expr_offset.to_string(context.config),
1711 fn rewrite_tuple_in_visual_indent_style<'a, T>(
1712 context: &RewriteContext,
1718 T: Rewrite + Spanned + ToExpr + 'a,
1720 let mut items = items.iter();
1721 // In case of length 1, need a trailing comma
1722 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1723 if items.len() == 1 {
1725 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1729 .rewrite(context, nested_shape)
1730 .map(|s| format!("({},)", s));
1733 let list_lo = context.snippet_provider.span_after(span, "(");
1734 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1735 let items = itemize_list(
1736 context.snippet_provider,
1740 |item| item.span().lo(),
1741 |item| item.span().hi(),
1742 |item| item.rewrite(context, nested_shape),
1744 span.hi() - BytePos(1),
1747 let item_vec: Vec<_> = items.collect();
1748 let tactic = definitive_tactic(
1750 ListTactic::HorizontalVertical,
1754 let fmt = ListFormatting::new(shape, context.config)
1756 .ends_with_newline(false);
1757 let list_str = write_list(&item_vec, &fmt)?;
1759 Some(format!("({})", list_str))
1762 pub fn rewrite_tuple<'a, T>(
1763 context: &RewriteContext,
1769 T: Rewrite + Spanned + ToExpr + 'a,
1771 debug!("rewrite_tuple {:?}", shape);
1772 if context.use_block_indent() {
1773 // We use the same rule as function calls for rewriting tuples.
1774 let force_tactic = if context.inside_macro() {
1775 if span_ends_with_comma(context, span) {
1776 Some(SeparatorTactic::Always)
1778 Some(SeparatorTactic::Never)
1780 } else if items.len() == 1 {
1781 Some(SeparatorTactic::Always)
1785 overflow::rewrite_with_parens(
1791 context.config.width_heuristics().fn_call_width,
1795 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
1799 pub fn rewrite_unary_prefix<R: Rewrite>(
1800 context: &RewriteContext,
1804 ) -> Option<String> {
1806 .rewrite(context, shape.offset_left(prefix.len())?)
1807 .map(|r| format!("{}{}", prefix, r))
1810 // FIXME: this is probably not correct for multi-line Rewrites. we should
1811 // subtract suffix.len() from the last line budget, not the first!
1812 pub fn rewrite_unary_suffix<R: Rewrite>(
1813 context: &RewriteContext,
1817 ) -> Option<String> {
1819 .rewrite(context, shape.sub_width(suffix.len())?)
1826 fn rewrite_unary_op(
1827 context: &RewriteContext,
1831 ) -> Option<String> {
1832 // For some reason, an UnOp is not spanned like BinOp!
1833 let operator_str = match *op {
1834 ast::UnOp::Deref => "*",
1835 ast::UnOp::Not => "!",
1836 ast::UnOp::Neg => "-",
1838 rewrite_unary_prefix(context, operator_str, expr, shape)
1841 fn rewrite_assignment(
1842 context: &RewriteContext,
1845 op: Option<&ast::BinOp>,
1847 ) -> Option<String> {
1848 let operator_str = match op {
1849 Some(op) => context.snippet(op.span),
1853 // 1 = space between lhs and operator.
1854 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1855 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1857 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1860 /// Controls where to put the rhs.
1861 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1862 pub enum RhsTactics {
1865 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1866 ForceNextLineWithoutIndent,
1869 // The left hand side must contain everything up to, and including, the
1870 // assignment operator.
1871 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1872 context: &RewriteContext,
1876 ) -> Option<String> {
1877 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1880 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1881 context: &RewriteContext,
1885 rhs_tactics: RhsTactics,
1886 ) -> Option<String> {
1887 let lhs = lhs.into();
1888 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1889 shape.indent.width()
1893 // 1 = space between operator and rhs.
1894 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1896 offset: shape.offset + last_line_width + 1,
1899 let rhs = choose_rhs(
1903 ex.rewrite(context, orig_shape),
1909 fn choose_rhs<R: Rewrite>(
1910 context: &RewriteContext,
1913 orig_rhs: Option<String>,
1914 rhs_tactics: RhsTactics,
1915 ) -> Option<String> {
1917 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1918 Some(format!(" {}", new_str))
1921 // Expression did not fit on the same line as the identifier.
1922 // Try splitting the line and see if that works better.
1923 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1924 let new_rhs = expr.rewrite(context, new_shape);
1925 let new_indent_str = &shape
1927 .block_indent(context.config)
1928 .to_string_with_newline(context.config);
1930 match (orig_rhs, new_rhs) {
1931 (Some(ref orig_rhs), Some(ref new_rhs))
1932 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1935 Some(format!(" {}", orig_rhs))
1937 (Some(ref orig_rhs), Some(ref new_rhs))
1938 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1940 Some(format!("{}{}", new_indent_str, new_rhs))
1942 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1943 (None, None) => None,
1944 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1950 fn shape_from_rhs_tactic(
1951 context: &RewriteContext,
1953 rhs_tactic: RhsTactics,
1954 ) -> Option<Shape> {
1956 RhsTactics::ForceNextLineWithoutIndent => Some(shape.with_max_width(context.config)),
1957 RhsTactics::Default => {
1958 Shape::indented(shape.indent.block_indent(context.config), context.config)
1959 .sub_width(shape.rhs_overhead(context.config))
1964 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
1965 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1966 || !next_line_rhs.contains('\n')
1967 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
1968 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
1969 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
1970 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
1973 fn rewrite_expr_addrof(
1974 context: &RewriteContext,
1975 mutability: ast::Mutability,
1978 ) -> Option<String> {
1979 let operator_str = match mutability {
1980 ast::Mutability::Immutable => "&",
1981 ast::Mutability::Mutable => "&mut ",
1983 rewrite_unary_prefix(context, operator_str, expr, shape)
1987 fn to_expr(&self) -> Option<&ast::Expr>;
1988 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
1991 impl ToExpr for ast::Expr {
1992 fn to_expr(&self) -> Option<&ast::Expr> {
1996 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
1997 can_be_overflowed_expr(context, self, len)
2001 impl ToExpr for ast::Ty {
2002 fn to_expr(&self) -> Option<&ast::Expr> {
2006 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2007 can_be_overflowed_type(context, self, len)
2011 impl<'a> ToExpr for TuplePatField<'a> {
2012 fn to_expr(&self) -> Option<&ast::Expr> {
2016 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2017 can_be_overflowed_pat(context, self, len)
2021 impl<'a> ToExpr for ast::StructField {
2022 fn to_expr(&self) -> Option<&ast::Expr> {
2026 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2031 impl<'a> ToExpr for MacroArg {
2032 fn to_expr(&self) -> Option<&ast::Expr> {
2034 MacroArg::Expr(ref expr) => Some(expr),
2039 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2041 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2042 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2043 MacroArg::Pat(..) => false,
2044 MacroArg::Item(..) => len == 1,
2049 impl ToExpr for ast::GenericParam {
2050 fn to_expr(&self) -> Option<&ast::Expr> {
2054 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2059 pub fn is_method_call(expr: &ast::Expr) -> bool {
2061 ast::ExprKind::MethodCall(..) => true,
2062 ast::ExprKind::AddrOf(_, ref expr)
2063 | ast::ExprKind::Box(ref expr)
2064 | ast::ExprKind::Cast(ref expr, _)
2065 | ast::ExprKind::Try(ref expr)
2066 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),