1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use std::iter::repeat;
16 use syntax::{ast, ptr};
17 use syntax::codemap::{BytePos, CodeMap, Span};
19 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23 rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle};
25 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
26 struct_lit_shape, struct_lit_tactic, write_list, ListFormatting, ListItem, Separator};
27 use macros::{rewrite_macro, MacroArg, MacroPosition};
29 use patterns::{can_be_overflowed_pat, TuplePatField};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
33 use string::{rewrite_string, StringFormat};
34 use types::{can_be_overflowed_type, rewrite_path, PathContext};
35 use utils::{colon_spaces, contains_skip, count_newlines, extra_offset, first_line_width,
36 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
37 paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, trimmed_last_line_width,
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
42 impl Rewrite for ast::Expr {
43 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44 format_expr(self, ExprType::SubExpression, context, shape)
48 #[derive(Copy, Clone, PartialEq)]
57 context: &RewriteContext,
60 skip_out_of_file_lines_range!(context, expr.span);
62 if contains_skip(&*expr.attrs) {
63 return Some(context.snippet(expr.span()).to_owned());
66 let expr_rw = match expr.node {
67 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
68 &ptr_vec_to_ref_vec(expr_vec),
70 context.snippet_provider.span_after(expr.span, "["),
77 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
78 ast::ExprKind::Call(ref callee, ref args) => {
79 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
80 let callee_str = callee.rewrite(context, shape)?;
81 rewrite_call(context, &callee_str, args, inner_span, shape)
83 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
84 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
85 // FIXME: format comments between operands and operator
89 PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
92 context.config.binop_separator(),
95 ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
96 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
100 base.as_ref().map(|e| &**e),
104 ast::ExprKind::Tup(ref items) => {
105 rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
107 ast::ExprKind::If(..)
108 | ast::ExprKind::IfLet(..)
109 | ast::ExprKind::ForLoop(..)
110 | ast::ExprKind::Loop(..)
111 | ast::ExprKind::While(..)
112 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
113 .and_then(|control_flow| control_flow.rewrite(context, shape)),
114 ast::ExprKind::Block(ref block) => {
116 ExprType::Statement => {
117 if is_unsafe_block(block) {
118 block.rewrite(context, shape)
119 } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
120 // Rewrite block without trying to put it in a single line.
123 let prefix = block_prefix(context, block, shape)?;
124 rewrite_block_with_visitor(context, &prefix, block, shape, true)
127 ExprType::SubExpression => block.rewrite(context, shape),
130 ast::ExprKind::Match(ref cond, ref arms) => {
131 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
133 ast::ExprKind::Path(ref qself, ref path) => {
134 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
136 ast::ExprKind::Assign(ref lhs, ref rhs) => {
137 rewrite_assignment(context, lhs, rhs, None, shape)
139 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
140 rewrite_assignment(context, lhs, rhs, Some(op), shape)
142 ast::ExprKind::Continue(ref opt_label) => {
143 let id_str = match *opt_label {
144 Some(label) => format!(" {}", label.ident),
145 None => String::new(),
147 Some(format!("continue{}", id_str))
149 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
150 let id_str = match *opt_label {
151 Some(label) => format!(" {}", label.ident),
152 None => String::new(),
155 if let Some(ref expr) = *opt_expr {
156 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
158 Some(format!("break{}", id_str))
161 ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
162 rewrite_unary_prefix(context, "yield ", &**expr, shape)
164 Some("yield".to_string())
166 ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) => {
167 closures::rewrite_closure(
177 ast::ExprKind::Try(..)
178 | ast::ExprKind::Field(..)
179 | ast::ExprKind::TupField(..)
180 | ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
181 ast::ExprKind::Mac(ref mac) => {
182 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
184 context.snippet(expr.span).to_owned(),
185 context.config.max_width(),
190 ast::ExprKind::Ret(None) => Some("return".to_owned()),
191 ast::ExprKind::Ret(Some(ref expr)) => {
192 rewrite_unary_prefix(context, "return ", &**expr, shape)
194 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
195 ast::ExprKind::AddrOf(mutability, ref expr) => {
196 rewrite_expr_addrof(context, mutability, expr, shape)
198 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
201 PairParts::new("", " as ", ""),
204 SeparatorPlace::Front,
206 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
209 PairParts::new("", ": ", ""),
212 SeparatorPlace::Back,
214 ast::ExprKind::Index(ref expr, ref index) => {
215 rewrite_index(&**expr, &**index, context, shape)
217 ast::ExprKind::Repeat(ref expr, ref repeats) => {
218 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
226 PairParts::new(lbr, "; ", rbr),
229 SeparatorPlace::Back,
232 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
233 let delim = match limits {
234 ast::RangeLimits::HalfOpen => "..",
235 ast::RangeLimits::Closed => "..=",
238 fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
240 ast::ExprKind::Lit(ref lit) => match lit.node {
241 ast::LitKind::FloatUnsuffixed(..) => {
242 context.snippet(lit.span).ends_with('.')
250 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
251 (Some(lhs), Some(rhs)) => {
252 let sp_delim = if context.config.spaces_around_ranges() {
253 format!(" {} ", delim)
254 } else if needs_space_before_range(context, lhs) {
255 format!(" {}", delim)
262 PairParts::new("", &sp_delim, ""),
265 context.config.binop_separator(),
268 (None, Some(rhs)) => {
269 let sp_delim = if context.config.spaces_around_ranges() {
270 format!("{} ", delim)
274 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
276 (Some(lhs), None) => {
277 let sp_delim = if context.config.spaces_around_ranges() {
278 format!(" {}", delim)
282 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
284 (None, None) => Some(delim.to_owned()),
287 // We do not format these expressions yet, but they should still
288 // satisfy our width restrictions.
289 ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
290 Some(context.snippet(expr.span).to_owned())
292 ast::ExprKind::Catch(ref block) => {
293 if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
297 let budget = shape.width.checked_sub(9).unwrap_or(0);
301 block.rewrite(context, Shape::legacy(budget, shape.indent))?
308 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
309 .and_then(|expr_str| {
310 let attrs = outer_attributes(&expr.attrs);
311 let attrs_str = attrs.rewrite(context, shape)?;
313 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
316 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
320 #[derive(new, Clone, Copy)]
321 pub struct PairParts<'a> {
327 pub fn rewrite_pair<LHS, RHS>(
331 context: &RewriteContext,
333 separator_place: SeparatorPlace,
339 let lhs_overhead = match separator_place {
340 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
341 SeparatorPlace::Front => shape.used_width(),
343 let lhs_shape = Shape {
344 width: context.budget(lhs_overhead),
347 let lhs_result = lhs.rewrite(context, lhs_shape)
348 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
350 // Try to the both lhs and rhs on the same line.
351 let rhs_orig_result = shape
352 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
353 .and_then(|s| s.sub_width(pp.suffix.len()))
354 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
355 if let Some(ref rhs_result) = rhs_orig_result {
356 // If the rhs looks like block expression, we allow it to stay on the same line
357 // with the lhs even if it is multi-lined.
358 let allow_same_line = rhs_result
361 .map(|first_line| first_line.ends_with('{'))
363 if !rhs_result.contains('\n') || allow_same_line {
364 let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
365 + first_line_width(rhs_result) + pp.suffix.len();
366 if one_line_width <= shape.width {
369 lhs_result, pp.infix, rhs_result, pp.suffix
375 // We have to use multiple lines.
376 // Re-evaluate the rhs because we have more space now:
377 let mut rhs_shape = match context.config.indent_style() {
378 IndentStyle::Visual => shape
379 .sub_width(pp.suffix.len() + pp.prefix.len())?
380 .visual_indent(pp.prefix.len()),
381 IndentStyle::Block => {
382 // Try to calculate the initial constraint on the right hand side.
383 let rhs_overhead = shape.rhs_overhead(context.config);
384 Shape::indented(shape.indent.block_indent(context.config), context.config)
385 .sub_width(rhs_overhead)?
388 let infix = match separator_place {
389 SeparatorPlace::Back => pp.infix.trim_right(),
390 SeparatorPlace::Front => pp.infix.trim_left(),
392 if separator_place == SeparatorPlace::Front {
393 rhs_shape = rhs_shape.offset_left(infix.len())?;
395 let rhs_result = rhs.rewrite(context, rhs_shape)?;
396 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
397 let infix_with_sep = match separator_place {
398 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
399 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
403 lhs_result, infix_with_sep, rhs_result, pp.suffix
407 pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
410 context: &RewriteContext,
412 trailing_comma: bool,
413 ) -> Option<String> {
414 let bracket_size = if context.config.spaces_within_parens_and_brackets() {
420 let nested_shape = match context.config.indent_style() {
421 IndentStyle::Block => shape
423 .block_indent(context.config.tab_spaces())
424 .with_max_width(context.config)
426 IndentStyle::Visual => shape
427 .visual_indent(bracket_size)
428 .sub_width(bracket_size * 2)?,
431 let items = itemize_list(
432 context.snippet_provider,
436 |item| item.span().lo(),
437 |item| item.span().hi(),
438 |item| item.rewrite(context, nested_shape),
442 ).collect::<Vec<_>>();
444 if items.is_empty() {
445 if context.config.spaces_within_parens_and_brackets() {
446 return Some("[ ]".to_string());
448 return Some("[]".to_string());
452 let tactic = array_tactic(context, shape, nested_shape, exprs, &items, bracket_size);
453 let ends_with_newline = tactic.ends_with_newline(context.config.indent_style());
455 let fmt = ListFormatting {
458 trailing_separator: if trailing_comma {
459 SeparatorTactic::Always
460 } else if context.inside_macro && !exprs.is_empty() {
461 let ends_with_bracket = context.snippet(span).ends_with(']');
462 let bracket_offset = if ends_with_bracket { 1 } else { 0 };
463 let snippet = context.snippet(mk_sp(span.lo(), span.hi() - BytePos(bracket_offset)));
464 let last_char_index = snippet.rfind(|c: char| !c.is_whitespace())?;
465 if &snippet[last_char_index..last_char_index + 1] == "," {
466 SeparatorTactic::Always
468 SeparatorTactic::Never
470 } else if context.config.indent_style() == IndentStyle::Visual {
471 SeparatorTactic::Never
473 SeparatorTactic::Vertical
475 separator_place: SeparatorPlace::Back,
478 preserve_newline: false,
479 config: context.config,
481 let list_str = write_list(&items, &fmt)?;
483 let result = if context.config.indent_style() == IndentStyle::Visual
484 || tactic == DefinitiveListTactic::Horizontal
486 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
487 format!("[ {} ]", list_str)
489 format!("[{}]", list_str)
494 nested_shape.indent.to_string_with_newline(context.config),
496 shape.block().indent.to_string_with_newline(context.config)
503 fn array_tactic<T: Rewrite + Spanned + ToExpr>(
504 context: &RewriteContext,
510 ) -> DefinitiveListTactic {
511 let has_long_item = items
513 .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
515 match context.config.indent_style() {
516 IndentStyle::Block => {
517 let tactic = match shape.width.checked_sub(2 * bracket_size) {
519 let tactic = ListTactic::LimitedHorizontalVertical(
520 context.config.width_heuristics().array_width,
522 definitive_tactic(items, tactic, Separator::Comma, width)
524 None => DefinitiveListTactic::Vertical,
526 if tactic == DefinitiveListTactic::Vertical && !has_long_item
527 && is_every_expr_simple(exprs)
529 DefinitiveListTactic::Mixed
534 IndentStyle::Visual => {
535 if has_long_item || items.iter().any(ListItem::is_multiline) {
538 ListTactic::LimitedHorizontalVertical(
539 context.config.width_heuristics().array_width,
545 DefinitiveListTactic::Mixed
551 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
552 debug!("nop_block_collapse {:?} {}", block_str, budget);
553 block_str.map(|block_str| {
554 if block_str.starts_with('{') && budget >= 2
555 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
564 fn rewrite_empty_block(
565 context: &RewriteContext,
568 ) -> Option<String> {
569 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
571 return Some("{}".to_owned());
574 // If a block contains only a single-line comment, then leave it on one line.
575 let user_str = context.snippet(block.span);
576 let user_str = user_str.trim();
577 if user_str.starts_with('{') && user_str.ends_with('}') {
578 let comment_str = user_str[1..user_str.len() - 1].trim();
579 if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
580 && comment_str.len() + 4 <= shape.width
582 return Some(format!("{{ {} }}", comment_str));
589 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
590 Some(match block.rules {
591 ast::BlockCheckMode::Unsafe(..) => {
592 let snippet = context.snippet(block.span);
593 let open_pos = snippet.find_uncommented("{")?;
594 // Extract comment between unsafe and block start.
595 let trimmed = &snippet[6..open_pos].trim();
597 if !trimmed.is_empty() {
598 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
599 let budget = shape.width.checked_sub(9)?;
605 Shape::legacy(budget, shape.indent + 7),
613 ast::BlockCheckMode::Default => String::new(),
617 fn rewrite_single_line_block(
618 context: &RewriteContext,
622 ) -> Option<String> {
623 if is_simple_block(block, context.codemap) {
624 let expr_shape = shape.offset_left(last_line_width(prefix))?;
625 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
626 let result = format!("{}{{ {} }}", prefix, expr_str);
627 if result.len() <= shape.width && !result.contains('\n') {
634 pub fn rewrite_block_with_visitor(
635 context: &RewriteContext,
640 ) -> Option<String> {
641 if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
645 let mut visitor = FmtVisitor::from_context(context);
646 visitor.block_indent = shape.indent;
647 visitor.is_if_else_block = context.is_if_else_block;
649 ast::BlockCheckMode::Unsafe(..) => {
650 let snippet = context.snippet(block.span);
651 let open_pos = snippet.find_uncommented("{")?;
652 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
654 ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
657 visitor.visit_block(block, None, has_braces);
658 Some(format!("{}{}", prefix, visitor.buffer))
661 impl Rewrite for ast::Block {
662 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
663 // shape.width is used only for the single line case: either the empty block `{}`,
664 // or an unsafe expression `unsafe { e }`.
665 if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
669 let prefix = block_prefix(context, self, shape)?;
671 let result = rewrite_block_with_visitor(context, &prefix, self, shape, true);
672 if let Some(ref result_str) = result {
673 if result_str.lines().count() <= 3 {
674 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
684 impl Rewrite for ast::Stmt {
685 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
686 skip_out_of_file_lines_range!(context, self.span());
688 let result = match self.node {
689 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
690 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
691 let suffix = if semicolon_for_stmt(context, self) {
697 let shape = shape.sub_width(suffix.len())?;
698 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
700 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
702 result.and_then(|res| recover_comment_removed(res, self.span(), context))
706 // Rewrite condition if the given expression has one.
707 pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
709 ast::ExprKind::Match(ref cond, _) => {
711 let cond_shape = match context.config.indent_style() {
712 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
713 IndentStyle::Block => shape.offset_left(8)?,
715 cond.rewrite(context, cond_shape)
717 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
719 String::from("\n") + &shape.indent.block_only().to_string(context.config);
721 .rewrite_cond(context, shape, &alt_block_sep)
722 .and_then(|rw| Some(rw.0))
727 // Abstraction over control flow expressions
729 struct ControlFlow<'a> {
730 cond: Option<&'a ast::Expr>,
731 block: &'a ast::Block,
732 else_block: Option<&'a ast::Expr>,
733 label: Option<ast::Label>,
734 pats: Vec<&'a ast::Pat>,
738 allow_single_line: bool,
739 // True if this is an `if` expression in an `else if` :-( hacky
744 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
746 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
750 else_block.as_ref().map(|e| &**e),
751 expr_type == ExprType::SubExpression,
755 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
756 Some(ControlFlow::new_if(
758 ptr_vec_to_ref_vec(pat),
760 else_block.as_ref().map(|e| &**e),
761 expr_type == ExprType::SubExpression,
766 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
767 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
769 ast::ExprKind::Loop(ref block, label) => {
770 Some(ControlFlow::new_loop(block, label, expr.span))
772 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
779 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
780 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
786 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
794 impl<'a> ControlFlow<'a> {
797 pats: Vec<&'a ast::Pat>,
798 block: &'a ast::Block,
799 else_block: Option<&'a ast::Expr>,
800 allow_single_line: bool,
803 ) -> ControlFlow<'a> {
804 let matcher = choose_matcher(&pats);
820 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
830 allow_single_line: false,
837 pats: Vec<&'a ast::Pat>,
839 block: &'a ast::Block,
840 label: Option<ast::Label>,
842 ) -> ControlFlow<'a> {
843 let matcher = choose_matcher(&pats);
853 allow_single_line: false,
862 block: &'a ast::Block,
863 label: Option<ast::Label>,
865 ) -> ControlFlow<'a> {
875 allow_single_line: false,
881 fn rewrite_single_line(
884 context: &RewriteContext,
886 ) -> Option<String> {
887 assert!(self.allow_single_line);
888 let else_block = self.else_block?;
889 let fixed_cost = self.keyword.len() + " { } else { }".len();
891 if let ast::ExprKind::Block(ref else_node) = else_block.node {
892 if !is_simple_block(self.block, context.codemap)
893 || !is_simple_block(else_node, context.codemap)
894 || pat_expr_str.contains('\n')
899 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
900 let expr = &self.block.stmts[0];
901 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
903 let new_width = new_width.checked_sub(if_str.len())?;
904 let else_expr = &else_node.stmts[0];
905 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
907 if if_str.contains('\n') || else_str.contains('\n') {
911 let result = format!(
912 "{} {} {{ {} }} else {{ {} }}",
913 self.keyword, pat_expr_str, if_str, else_str
916 if result.len() <= width {
925 impl<'a> ControlFlow<'a> {
928 context: &RewriteContext,
932 ) -> Option<String> {
933 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
935 let cond_shape = shape.offset_left(offset)?;
936 if !self.pats.is_empty() {
937 let matcher = if self.matcher.is_empty() {
938 self.matcher.to_owned()
940 format!("{} ", self.matcher)
942 let pat_shape = cond_shape
943 .offset_left(matcher.len())?
944 .sub_width(self.connector.len())?;
945 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
946 let result = format!("{}{}{}", matcher, pat_string, self.connector);
947 return rewrite_assign_rhs(context, result, expr, cond_shape);
950 let expr_rw = expr.rewrite(context, cond_shape);
951 // The expression may (partially) fit on the current line.
952 // We do not allow splitting between `if` and condition.
953 if self.keyword == "if" || expr_rw.is_some() {
957 // The expression won't fit on the current line, jump to next.
958 let nested_shape = shape
959 .block_indent(context.config.tab_spaces())
960 .with_max_width(context.config);
961 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
962 expr.rewrite(context, nested_shape)
963 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
968 context: &RewriteContext,
971 ) -> Option<(String, usize)> {
972 // Do not take the rhs overhead from the upper expressions into account
973 // when rewriting pattern.
974 let new_width = context.budget(shape.used_width());
975 let fresh_shape = Shape {
979 let constr_shape = if self.nested_if {
980 // We are part of an if-elseif-else chain. Our constraints are tightened.
981 // 7 = "} else " .len()
982 fresh_shape.offset_left(7)?
987 let label_string = rewrite_label(self.label);
988 // 1 = space after keyword.
989 let offset = self.keyword.len() + label_string.len() + 1;
991 let pat_expr_string = match self.cond {
992 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
993 None => String::new(),
997 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1003 let one_line_budget = context
1006 .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1008 let force_newline_brace = (pat_expr_string.contains('\n')
1009 || pat_expr_string.len() > one_line_budget)
1010 && !last_line_extendable(&pat_expr_string);
1012 // Try to format if-else on single line.
1013 if self.allow_single_line
1017 .single_line_if_else_max_width > 0
1019 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1021 if let Some(cond_str) = trial {
1026 .single_line_if_else_max_width
1028 return Some((cond_str, 0));
1033 let cond_span = if let Some(cond) = self.cond {
1036 mk_sp(self.block.span.lo(), self.block.span.lo())
1039 // `for event in event`
1040 // Do not include label in the span.
1041 let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1042 let between_kwd_cond = mk_sp(
1045 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1046 if self.pats.is_empty() {
1048 } else if self.matcher.is_empty() {
1049 self.pats[0].span.lo()
1053 .span_before(self.span, self.matcher.trim())
1057 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1059 let after_cond_comment =
1060 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1062 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1064 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1065 || force_newline_brace
1072 let used_width = if pat_expr_string.contains('\n') {
1073 last_line_width(&pat_expr_string)
1075 // 2 = spaces after keyword and condition.
1076 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1084 between_kwd_cond_comment.as_ref().map_or(
1085 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1093 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1100 impl<'a> Rewrite for ControlFlow<'a> {
1101 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1102 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1104 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1105 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1106 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1107 if used_width == 0 {
1108 return Some(cond_str);
1111 let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1112 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1113 // we should avoid the single line case.
1114 let block_width = if self.else_block.is_some() || self.nested_if {
1119 let block_shape = Shape {
1123 let mut block_context = context.clone();
1124 block_context.is_if_else_block = self.else_block.is_some();
1126 rewrite_block_with_visitor(&block_context, "", self.block, block_shape, true)?;
1128 let mut result = format!("{}{}", cond_str, block_str);
1130 if let Some(else_block) = self.else_block {
1131 let shape = Shape::indented(shape.indent, context.config);
1132 let mut last_in_chain = false;
1133 let rewrite = match else_block.node {
1134 // If the else expression is another if-else expression, prevent it
1135 // from being formatted on a single line.
1136 // Note how we're passing the original shape, as the
1137 // cost of "else" should not cascade.
1138 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1139 ControlFlow::new_if(
1141 ptr_vec_to_ref_vec(pat),
1143 next_else_block.as_ref().map(|e| &**e),
1146 mk_sp(else_block.span.lo(), self.span.hi()),
1147 ).rewrite(context, shape)
1149 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1150 ControlFlow::new_if(
1154 next_else_block.as_ref().map(|e| &**e),
1157 mk_sp(else_block.span.lo(), self.span.hi()),
1158 ).rewrite(context, shape)
1161 last_in_chain = true;
1162 // When rewriting a block, the width is only used for single line
1163 // blocks, passing 1 lets us avoid that.
1164 let else_shape = Shape {
1165 width: min(1, shape.width),
1168 format_expr(else_block, ExprType::Statement, context, else_shape)
1172 let between_kwd_else_block = mk_sp(
1173 self.block.span.hi(),
1176 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1178 let between_kwd_else_block_comment =
1179 extract_comment(between_kwd_else_block, context, shape);
1181 let after_else = mk_sp(
1184 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1185 else_block.span.lo(),
1187 let after_else_comment = extract_comment(after_else, context, shape);
1189 let between_sep = match context.config.control_brace_style() {
1190 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1193 ControlBraceStyle::AlwaysSameLine => " ",
1195 let after_sep = match context.config.control_brace_style() {
1196 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1200 result.push_str(&format!(
1202 between_kwd_else_block_comment
1204 .map_or(between_sep, |s| &**s),
1205 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1207 result.push_str(&rewrite?);
1214 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1216 Some(label) => Cow::from(format!("{}: ", label.ident)),
1217 None => Cow::from(""),
1221 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1222 match rewrite_missing_comment(span, shape, context) {
1223 Some(ref comment) if !comment.is_empty() => Some(format!(
1224 "{indent}{}{indent}",
1226 indent = shape.indent.to_string_with_newline(context.config)
1232 pub fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1233 let snippet = codemap.span_to_snippet(block.span).unwrap();
1234 contains_comment(&snippet)
1237 // Checks that a block contains no statements, an expression and no comments.
1238 // FIXME: incorrectly returns false when comment is contained completely within
1240 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1241 (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1242 && !block_contains_comment(block, codemap))
1245 /// Checks whether a block contains at most one statement or expression, and no comments.
1246 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1247 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1250 /// Checks whether a block contains no statements, expressions, or comments.
1251 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1252 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1255 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1257 ast::StmtKind::Expr(..) => true,
1262 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1263 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1270 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
1271 struct ArmWrapper<'a> {
1272 pub arm: &'a ast::Arm,
1273 /// True if the arm is the last one in match expression. Used to decide on whether we should add
1274 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
1276 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
1277 pub beginning_vert: Option<BytePos>,
1280 impl<'a> ArmWrapper<'a> {
1284 beginning_vert: Option<BytePos>,
1285 ) -> ArmWrapper<'a> {
1294 impl<'a> Spanned for ArmWrapper<'a> {
1295 fn span(&self) -> Span {
1296 if let Some(lo) = self.beginning_vert {
1297 mk_sp(lo, self.arm.span().hi())
1304 impl<'a> Rewrite for ArmWrapper<'a> {
1305 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1306 rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
1311 context: &RewriteContext,
1316 attrs: &[ast::Attribute],
1317 ) -> Option<String> {
1318 // Do not take the rhs overhead from the upper expressions into account
1319 // when rewriting match condition.
1320 let cond_shape = Shape {
1321 width: context.budget(shape.used_width()),
1325 let cond_shape = match context.config.indent_style() {
1326 IndentStyle::Visual => cond_shape.shrink_left(6)?,
1327 IndentStyle::Block => cond_shape.offset_left(6)?,
1329 let cond_str = cond.rewrite(context, cond_shape)?;
1330 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1331 let block_sep = match context.config.control_brace_style() {
1332 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
1333 _ if last_line_extendable(&cond_str) => " ",
1335 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
1339 let nested_indent_str = shape
1341 .block_indent(context.config)
1342 .to_string(context.config);
1343 // Inner attributes.
1344 let inner_attrs = &inner_attributes(attrs);
1345 let inner_attrs_str = if inner_attrs.is_empty() {
1349 .rewrite(context, shape)
1350 .map(|s| format!("{}{}\n", nested_indent_str, s))?
1353 let open_brace_pos = if inner_attrs.is_empty() {
1354 let hi = if arms.is_empty() {
1361 .span_after(mk_sp(cond.span.hi(), hi), "{")
1363 inner_attrs[inner_attrs.len() - 1].span().hi()
1366 if arms.is_empty() {
1367 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1368 if snippet.trim().is_empty() {
1369 Some(format!("match {} {{}}", cond_str))
1371 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1372 Some(context.snippet(span).to_owned())
1376 "match {}{}{{\n{}{}{}\n{}}}",
1381 rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1382 shape.indent.to_string(context.config),
1387 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1388 if is_last && config.trailing_comma() == SeparatorTactic::Never {
1390 } else if config.match_block_trailing_comma() {
1392 } else if let ast::ExprKind::Block(ref block) = body.node {
1393 if let ast::BlockCheckMode::Default = block.rules {
1403 /// Collect a byte position of the beginning `|` for each arm, if available.
1404 fn collect_beginning_verts(
1405 context: &RewriteContext,
1408 ) -> Vec<Option<BytePos>> {
1409 let mut beginning_verts = Vec::with_capacity(arms.len());
1410 let mut lo = context.snippet_provider.span_after(span, "{");
1412 let hi = arm.pats[0].span.lo();
1413 let missing_span = mk_sp(lo, hi);
1414 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
1415 lo = arm.span().hi();
1420 fn rewrite_match_arms(
1421 context: &RewriteContext,
1425 open_brace_pos: BytePos,
1426 ) -> Option<String> {
1427 let arm_shape = shape
1428 .block_indent(context.config.tab_spaces())
1429 .with_max_width(context.config);
1431 let arm_len = arms.len();
1432 let is_last_iter = repeat(false)
1433 .take(arm_len.checked_sub(1).unwrap_or(0))
1434 .chain(repeat(true));
1435 let beginning_verts = collect_beginning_verts(context, arms, span);
1436 let items = itemize_list(
1437 context.snippet_provider,
1440 .zip(beginning_verts.into_iter())
1441 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
1444 |arm| arm.span().lo(),
1445 |arm| arm.span().hi(),
1446 |arm| arm.rewrite(context, arm_shape),
1451 let arms_vec: Vec<_> = items.collect();
1452 let fmt = ListFormatting {
1453 tactic: DefinitiveListTactic::Vertical,
1454 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1456 trailing_separator: SeparatorTactic::Never,
1457 separator_place: SeparatorPlace::Back,
1459 ends_with_newline: true,
1460 preserve_newline: true,
1461 config: context.config,
1464 write_list(&arms_vec, &fmt)
1467 fn rewrite_match_arm(
1468 context: &RewriteContext,
1472 beginning_vert: Option<BytePos>,
1473 ) -> Option<String> {
1474 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1475 if contains_skip(&arm.attrs) {
1476 let (_, body) = flatten_arm_body(context, &arm.body);
1477 // `arm.span()` does not include trailing comma, add it manually.
1478 return Some(format!(
1480 context.snippet(arm.span()),
1481 arm_comma(context.config, body, is_last),
1484 let missing_span = mk_sp(
1485 arm.attrs[arm.attrs.len() - 1].span.hi(),
1486 arm.pats[0].span.lo(),
1488 (missing_span, arm.attrs.rewrite(context, shape)?)
1490 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1492 let pats_str = rewrite_match_pattern(
1494 &ptr_vec_to_ref_vec(&arm.pats),
1496 beginning_vert.is_some(),
1498 ).and_then(|pats_str| {
1499 combine_strs_with_missing_comments(
1513 arm.guard.is_some(),
1518 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
1522 /// - `&[single-line, ntp]`
1525 /// - `[small, ntp]`
1526 /// - unary tuple constructor `([small, ntp])`
1528 fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
1529 // We also require that the pattern is reasonably 'small' with its literal width.
1530 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
1533 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
1535 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
1536 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
1537 ast::PatKind::Struct(..)
1538 | ast::PatKind::Mac(..)
1539 | ast::PatKind::Slice(..)
1540 | ast::PatKind::Path(..)
1541 | ast::PatKind::Range(..) => false,
1542 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
1543 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
1544 path.segments.len() <= 1 && subpats.len() <= 1
1546 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
1547 is_short_pattern_inner(&*p)
1552 fn rewrite_match_pattern(
1553 context: &RewriteContext,
1555 guard: &Option<ptr::P<ast::Expr>>,
1556 has_beginning_vert: bool,
1558 ) -> Option<String> {
1562 let pat_shape = shape
1564 .offset_left(if has_beginning_vert { 2 } else { 0 })?;
1565 let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
1566 let beginning_vert = if has_beginning_vert { "| " } else { "" };
1569 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1571 Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
1575 // @extend: true if the arm body can be put next to `=>`
1576 // @body: flattened body, if the body is block with a single expression
1577 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1579 ast::ExprKind::Block(ref block)
1580 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1582 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1584 !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
1592 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
1598 fn rewrite_match_body(
1599 context: &RewriteContext,
1600 body: &ptr::P<ast::Expr>,
1605 ) -> Option<String> {
1606 let (extend, body) = flatten_arm_body(context, body);
1607 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1608 (true, is_empty_block(block, context.codemap))
1613 let comma = arm_comma(context.config, body, is_last);
1614 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1616 let combine_orig_body = |body_str: &str| {
1617 let block_sep = match context.config.control_brace_style() {
1618 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1622 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1625 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1626 let next_line_indent = if !is_block || is_empty_block {
1627 shape.indent.block_indent(context.config)
1631 let combine_next_line_body = |body_str: &str| {
1633 return Some(format!(
1636 next_line_indent.to_string_with_newline(context.config),
1641 let indent_str = shape.indent.to_string_with_newline(context.config);
1642 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
1643 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
1644 let comma = if context.config.match_block_trailing_comma() {
1649 ("{", format!("{}}}{}", indent_str, comma))
1651 ("", String::from(","))
1654 let block_sep = match context.config.control_brace_style() {
1655 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
1656 _ if body_prefix.is_empty() => "".to_owned(),
1657 _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
1658 _ => format!(" {}", body_prefix),
1659 } + &nested_indent_str;
1663 pats_str, block_sep, body_str, body_suffix
1667 // Let's try and get the arm body on the same line as the condition.
1669 let orig_body_shape = shape
1670 .offset_left(extra_offset(pats_str, shape) + 4)
1671 .and_then(|shape| shape.sub_width(comma.len()));
1672 let orig_body = if let Some(body_shape) = orig_body_shape {
1673 let rewrite = nop_block_collapse(
1674 format_expr(body, ExprType::Statement, context, body_shape),
1680 if !forbid_same_line
1682 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1684 return combine_orig_body(body_str);
1691 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1693 // Try putting body on the next line and see if it looks better.
1694 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1695 let next_line_body = nop_block_collapse(
1696 format_expr(body, ExprType::Statement, context, next_line_body_shape),
1697 next_line_body_shape.width,
1699 match (orig_body, next_line_body) {
1700 (Some(ref orig_str), Some(ref next_line_str))
1701 if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1703 combine_next_line_body(next_line_str)
1705 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1706 combine_orig_body(orig_str)
1708 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1709 combine_next_line_body(next_line_str)
1711 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1712 (None, None) => None,
1713 (Some(ref orig_str), _) => combine_orig_body(orig_str),
1717 // The `if ...` guard on a match arm.
1719 context: &RewriteContext,
1720 guard: &Option<ptr::P<ast::Expr>>,
1722 // The amount of space used up on this line for the pattern in
1723 // the arm (excludes offset).
1724 pattern_width: usize,
1725 ) -> Option<String> {
1726 if let Some(ref guard) = *guard {
1727 // First try to fit the guard string on the same line as the pattern.
1728 // 4 = ` if `, 5 = ` => {`
1729 let cond_shape = shape
1730 .offset_left(pattern_width + 4)
1731 .and_then(|s| s.sub_width(5));
1732 if let Some(cond_shape) = cond_shape {
1733 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1734 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1735 return Some(format!(" if {}", cond_str));
1740 // Not enough space to put the guard after the pattern, try a newline.
1741 // 3 = `if `, 5 = ` => {`
1742 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1744 .and_then(|s| s.sub_width(5));
1745 if let Some(cond_shape) = cond_shape {
1746 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1747 return Some(format!(
1749 cond_shape.indent.to_string_with_newline(context.config),
1761 fn rewrite_multiple_patterns(
1762 context: &RewriteContext,
1765 ) -> Option<String> {
1766 let pat_strs = pats.iter()
1767 .map(|p| p.rewrite(context, shape))
1768 .collect::<Option<Vec<_>>>()?;
1770 let use_mixed_layout = pats.iter()
1771 .zip(pat_strs.iter())
1772 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1773 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1774 let tactic = if use_mixed_layout {
1775 DefinitiveListTactic::Mixed
1779 ListTactic::HorizontalVertical,
1780 Separator::VerticalBar,
1784 let fmt = ListFormatting {
1787 trailing_separator: SeparatorTactic::Never,
1788 separator_place: context.config.binop_separator(),
1790 ends_with_newline: false,
1791 preserve_newline: false,
1792 config: context.config,
1794 write_list(&items, &fmt)
1797 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
1799 // We do not allow `if` to stay on the same line, since we could easily mistake
1800 // `pat => if cond { ... }` and `pat if cond => { ... }`.
1801 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
1802 ast::ExprKind::ForLoop(..)
1803 | ast::ExprKind::Loop(..)
1804 | ast::ExprKind::While(..)
1805 | ast::ExprKind::WhileLet(..)
1806 | ast::ExprKind::Match(..)
1807 | ast::ExprKind::Block(..)
1808 | ast::ExprKind::Closure(..)
1809 | ast::ExprKind::Array(..)
1810 | ast::ExprKind::Call(..)
1811 | ast::ExprKind::MethodCall(..)
1812 | ast::ExprKind::Mac(..)
1813 | ast::ExprKind::Struct(..)
1814 | ast::ExprKind::Tup(..) => true,
1815 ast::ExprKind::AddrOf(_, ref expr)
1816 | ast::ExprKind::Box(ref expr)
1817 | ast::ExprKind::Try(ref expr)
1818 | ast::ExprKind::Unary(_, ref expr)
1819 | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
1824 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1826 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1828 context.snippet(l.span).to_owned(),
1829 context.config.max_width(),
1835 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1836 let string_lit = context.snippet(span);
1838 if !context.config.format_strings() {
1843 .all(|line| line.ends_with('\\'))
1845 let new_indent = shape.visual_indent(1).indent;
1846 let indented_string_lit = String::from(
1852 new_indent.to_string(context.config),
1856 .collect::<Vec<_>>()
1860 return wrap_str(indented_string_lit, context.config.max_width(), shape);
1862 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1866 // Remove the quote characters.
1867 let str_lit = &string_lit[1..string_lit.len() - 1];
1871 &StringFormat::new(shape.visual_indent(0), context.config),
1876 /// In case special-case style is required, returns an offset from which we start horizontal layout.
1877 pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
1878 if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
1880 .find(|&&(s, _)| s == callee_str)
1882 let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
1884 Some((all_simple, num_args_before))
1890 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
1893 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
1894 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
1895 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
1896 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
1897 // format! like macros
1898 // From the Rust Standard Library.
1902 ("format_args!", 0),
1906 ("unreachable!", 0),
1907 // From the `log` crate.
1912 // write! like macros
1914 ("debug_assert!", 1),
1917 // assert_eq! like macros
1920 ("debug_assert_eq!", 2),
1921 ("debug_assert_ne!", 2),
1924 pub fn rewrite_call(
1925 context: &RewriteContext,
1927 args: &[ptr::P<ast::Expr>],
1930 ) -> Option<String> {
1931 overflow::rewrite_with_parens(
1934 &ptr_vec_to_ref_vec(args),
1937 context.config.width_heuristics().fn_call_width,
1938 if context.inside_macro {
1939 if span_ends_with_comma(context, span) {
1940 Some(SeparatorTactic::Always)
1942 Some(SeparatorTactic::Never)
1950 fn is_simple_expr(expr: &ast::Expr) -> bool {
1952 ast::ExprKind::Lit(..) => true,
1953 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1954 ast::ExprKind::AddrOf(_, ref expr)
1955 | ast::ExprKind::Box(ref expr)
1956 | ast::ExprKind::Cast(ref expr, _)
1957 | ast::ExprKind::Field(ref expr, _)
1958 | ast::ExprKind::Try(ref expr)
1959 | ast::ExprKind::TupField(ref expr, _)
1960 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1961 ast::ExprKind::Index(ref lhs, ref rhs) | ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1962 is_simple_expr(lhs) && is_simple_expr(rhs)
1968 fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
1971 .all(|arg| arg.to_expr().map_or(false, is_simple_expr))
1974 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
1976 ast::ExprKind::Match(..) => {
1977 (context.use_block_indent() && args_len == 1)
1978 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1980 ast::ExprKind::If(..)
1981 | ast::ExprKind::IfLet(..)
1982 | ast::ExprKind::ForLoop(..)
1983 | ast::ExprKind::Loop(..)
1984 | ast::ExprKind::While(..)
1985 | ast::ExprKind::WhileLet(..) => {
1986 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1988 ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
1989 context.use_block_indent()
1990 || context.config.indent_style() == IndentStyle::Visual && args_len > 1
1992 ast::ExprKind::Array(..)
1993 | ast::ExprKind::Call(..)
1994 | ast::ExprKind::Mac(..)
1995 | ast::ExprKind::MethodCall(..)
1996 | ast::ExprKind::Struct(..)
1997 | ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
1998 ast::ExprKind::AddrOf(_, ref expr)
1999 | ast::ExprKind::Box(ref expr)
2000 | ast::ExprKind::Try(ref expr)
2001 | ast::ExprKind::Unary(_, ref expr)
2002 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2007 pub fn is_nested_call(expr: &ast::Expr) -> bool {
2009 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
2010 ast::ExprKind::AddrOf(_, ref expr)
2011 | ast::ExprKind::Box(ref expr)
2012 | ast::ExprKind::Try(ref expr)
2013 | ast::ExprKind::Unary(_, ref expr)
2014 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
2019 /// Return true if a function call or a method call represented by the given span ends with a
2020 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2021 /// comma from macro can potentially break the code.
2022 pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2023 let mut result: bool = Default::default();
2024 let mut prev_char: char = Default::default();
2026 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
2028 _ if kind.is_comment() || c.is_whitespace() => continue,
2029 ')' | '}' => result = result && prev_char != c,
2030 ',' => result = true,
2031 _ => result = false,
2040 context: &RewriteContext,
2041 mut subexpr: &ast::Expr,
2044 ) -> Option<String> {
2045 debug!("rewrite_paren, shape: {:?}", shape);
2047 // Extract comments within parens.
2048 let mut pre_comment;
2049 let mut post_comment;
2052 let pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
2053 let post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
2054 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
2055 post_comment = rewrite_missing_comment(post_span, shape, context)?;
2057 // Remove nested parens if there are no comments.
2058 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
2059 if pre_comment.is_empty() && post_comment.is_empty() {
2060 span = subexpr.span;
2061 subexpr = subsubexpr;
2069 let total_paren_overhead = paren_overhead(context);
2070 let paren_overhead = total_paren_overhead / 2;
2071 let sub_shape = shape
2072 .offset_left(paren_overhead)
2073 .and_then(|s| s.sub_width(paren_overhead))?;
2075 let paren_wrapper = |s: &str| {
2076 if context.config.spaces_within_parens_and_brackets() && !s.is_empty() {
2077 format!("( {}{}{} )", pre_comment, s, post_comment)
2079 format!("({}{}{})", pre_comment, s, post_comment)
2083 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2084 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2086 if subexpr_str.contains('\n')
2087 || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2089 Some(paren_wrapper(&subexpr_str))
2098 context: &RewriteContext,
2100 ) -> Option<String> {
2101 let expr_str = expr.rewrite(context, shape)?;
2103 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
2109 let offset = last_line_width(&expr_str) + lbr.len();
2110 let rhs_overhead = shape.rhs_overhead(context.config);
2111 let index_shape = if expr_str.contains('\n') {
2112 Shape::legacy(context.config.max_width(), shape.indent)
2113 .offset_left(offset)
2114 .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2116 shape.visual_indent(offset).sub_width(offset + rbr.len())
2118 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2120 // Return if index fits in a single line.
2121 match orig_index_rw {
2122 Some(ref index_str) if !index_str.contains('\n') => {
2123 return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2128 // Try putting index on the next line and see if it fits in a single line.
2129 let indent = shape.indent.block_indent(context.config);
2130 let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2131 let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2132 let new_index_rw = index.rewrite(context, index_shape);
2133 match (orig_index_rw, new_index_rw) {
2134 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2137 indent.to_string_with_newline(context.config),
2142 (None, Some(ref new_index_str)) => Some(format!(
2145 indent.to_string_with_newline(context.config),
2150 (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2155 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2160 fields.iter().all(|field| !field.is_shorthand)
2163 fn rewrite_struct_lit<'a>(
2164 context: &RewriteContext,
2166 fields: &'a [ast::Field],
2167 base: Option<&'a ast::Expr>,
2170 ) -> Option<String> {
2171 debug!("rewrite_struct_lit: shape {:?}", shape);
2173 enum StructLitField<'a> {
2174 Regular(&'a ast::Field),
2175 Base(&'a ast::Expr),
2179 let path_shape = shape.sub_width(2)?;
2180 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2182 if fields.is_empty() && base.is_none() {
2183 return Some(format!("{} {{}}", path_str));
2186 // Foo { a: Foo } - indent is +3, width is -5.
2187 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2189 let one_line_width = h_shape.map_or(0, |shape| shape.width);
2190 let body_lo = context.snippet_provider.span_after(span, "{");
2191 let fields_str = if struct_lit_can_be_aligned(fields, &base)
2192 && context.config.struct_field_align_threshold() > 0
2194 rewrite_with_alignment(
2198 mk_sp(body_lo, span.hi()),
2202 let field_iter = fields
2204 .map(StructLitField::Regular)
2205 .chain(base.into_iter().map(StructLitField::Base));
2207 let span_lo = |item: &StructLitField| match *item {
2208 StructLitField::Regular(field) => field.span().lo(),
2209 StructLitField::Base(expr) => {
2210 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2211 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2212 let pos = snippet.find_uncommented("..").unwrap();
2213 last_field_hi + BytePos(pos as u32)
2216 let span_hi = |item: &StructLitField| match *item {
2217 StructLitField::Regular(field) => field.span().hi(),
2218 StructLitField::Base(expr) => expr.span.hi(),
2220 let rewrite = |item: &StructLitField| match *item {
2221 StructLitField::Regular(field) => {
2222 // The 1 taken from the v_budget is for the comma.
2223 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2225 StructLitField::Base(expr) => {
2227 expr.rewrite(context, v_shape.offset_left(2)?)
2228 .map(|s| format!("..{}", s))
2232 let items = itemize_list(
2233 context.snippet_provider,
2244 let item_vec = items.collect::<Vec<_>>();
2246 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2247 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2249 let ends_with_comma = span_ends_with_comma(context, span);
2250 let force_no_trailing_comma = if context.inside_macro && !ends_with_comma {
2256 let fmt = struct_lit_formatting(
2260 force_no_trailing_comma || base.is_some(),
2263 write_list(&item_vec, &fmt)?
2266 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2267 Some(format!("{} {{{}}}", path_str, fields_str))
2269 // FIXME if context.config.indent_style() == Visual, but we run out
2270 // of space, we should fall back to BlockIndent.
2273 pub fn wrap_struct_field(
2274 context: &RewriteContext,
2277 nested_shape: Shape,
2278 one_line_width: usize,
2280 if context.config.indent_style() == IndentStyle::Block
2281 && (fields_str.contains('\n') || !context.config.struct_lit_single_line()
2282 || fields_str.len() > one_line_width)
2286 nested_shape.indent.to_string_with_newline(context.config),
2288 shape.indent.to_string_with_newline(context.config)
2291 // One liner or visual indent.
2292 format!(" {} ", fields_str)
2296 pub fn struct_lit_field_separator(config: &Config) -> &str {
2297 colon_spaces(config.space_before_colon(), config.space_after_colon())
2300 pub fn rewrite_field(
2301 context: &RewriteContext,
2304 prefix_max_width: usize,
2305 ) -> Option<String> {
2306 if contains_skip(&field.attrs) {
2307 return Some(context.snippet(field.span()).to_owned());
2309 let mut attrs_str = field.attrs.rewrite(context, shape)?;
2310 if !attrs_str.is_empty() {
2311 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
2313 let name = field.ident.node.to_string();
2314 if field.is_shorthand {
2315 Some(attrs_str + &name)
2317 let mut separator = String::from(struct_lit_field_separator(context.config));
2318 for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2319 separator.push(' ');
2321 let overhead = name.len() + separator.len();
2322 let expr_shape = shape.offset_left(overhead)?;
2323 let expr = field.expr.rewrite(context, expr_shape);
2326 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
2327 Some(attrs_str + &name)
2329 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2331 let expr_offset = shape.indent.block_indent(context.config);
2334 .rewrite(context, Shape::indented(expr_offset, context.config));
2340 expr_offset.to_string(context.config),
2349 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2350 context: &RewriteContext,
2356 T: Rewrite + Spanned + ToExpr + 'a,
2358 let mut items = items.iter();
2359 // In case of length 1, need a trailing comma
2360 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2361 if items.len() == 1 {
2363 let nested_shape = shape.sub_width(3)?.visual_indent(1);
2367 .rewrite(context, nested_shape)
2369 if context.config.spaces_within_parens_and_brackets() {
2370 format!("( {}, )", s)
2377 let list_lo = context.snippet_provider.span_after(span, "(");
2378 let nested_shape = shape.sub_width(2)?.visual_indent(1);
2379 let items = itemize_list(
2380 context.snippet_provider,
2384 |item| item.span().lo(),
2385 |item| item.span().hi(),
2386 |item| item.rewrite(context, nested_shape),
2388 span.hi() - BytePos(1),
2391 let item_vec: Vec<_> = items.collect();
2392 let tactic = definitive_tactic(
2394 ListTactic::HorizontalVertical,
2398 let fmt = ListFormatting {
2401 trailing_separator: SeparatorTactic::Never,
2402 separator_place: SeparatorPlace::Back,
2404 ends_with_newline: false,
2405 preserve_newline: false,
2406 config: context.config,
2408 let list_str = write_list(&item_vec, &fmt)?;
2410 if context.config.spaces_within_parens_and_brackets() && !list_str.is_empty() {
2411 Some(format!("( {} )", list_str))
2413 Some(format!("({})", list_str))
2417 pub fn rewrite_tuple<'a, T>(
2418 context: &RewriteContext,
2424 T: Rewrite + Spanned + ToExpr + 'a,
2426 debug!("rewrite_tuple {:?}", shape);
2427 if context.use_block_indent() {
2428 // We use the same rule as function calls for rewriting tuples.
2429 let force_tactic = if context.inside_macro {
2430 if span_ends_with_comma(context, span) {
2431 Some(SeparatorTactic::Always)
2433 Some(SeparatorTactic::Never)
2436 if items.len() == 1 {
2437 Some(SeparatorTactic::Always)
2442 overflow::rewrite_with_parens(
2448 context.config.width_heuristics().fn_call_width,
2452 rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2456 pub fn rewrite_unary_prefix<R: Rewrite>(
2457 context: &RewriteContext,
2461 ) -> Option<String> {
2463 .rewrite(context, shape.offset_left(prefix.len())?)
2464 .map(|r| format!("{}{}", prefix, r))
2467 // FIXME: this is probably not correct for multi-line Rewrites. we should
2468 // subtract suffix.len() from the last line budget, not the first!
2469 pub fn rewrite_unary_suffix<R: Rewrite>(
2470 context: &RewriteContext,
2474 ) -> Option<String> {
2476 .rewrite(context, shape.sub_width(suffix.len())?)
2483 fn rewrite_unary_op(
2484 context: &RewriteContext,
2488 ) -> Option<String> {
2489 // For some reason, an UnOp is not spanned like BinOp!
2490 let operator_str = match *op {
2491 ast::UnOp::Deref => "*",
2492 ast::UnOp::Not => "!",
2493 ast::UnOp::Neg => "-",
2495 rewrite_unary_prefix(context, operator_str, expr, shape)
2498 fn rewrite_assignment(
2499 context: &RewriteContext,
2502 op: Option<&ast::BinOp>,
2504 ) -> Option<String> {
2505 let operator_str = match op {
2506 Some(op) => context.snippet(op.span),
2510 // 1 = space between lhs and operator.
2511 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2512 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2514 rewrite_assign_rhs(context, lhs_str, rhs, shape)
2517 // The left hand side must contain everything up to, and including, the
2518 // assignment operator.
2519 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2520 context: &RewriteContext,
2524 ) -> Option<String> {
2525 let lhs = lhs.into();
2526 let last_line_width = last_line_width(&lhs)
2527 .checked_sub(if lhs.contains('\n') {
2528 shape.indent.width()
2533 // 1 = space between operator and rhs.
2534 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2536 offset: shape.offset + last_line_width + 1,
2539 let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2543 pub fn choose_rhs<R: Rewrite>(
2544 context: &RewriteContext,
2547 orig_rhs: Option<String>,
2548 ) -> Option<String> {
2550 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2551 Some(format!(" {}", new_str))
2554 // Expression did not fit on the same line as the identifier.
2555 // Try splitting the line and see if that works better.
2557 Shape::indented(shape.indent.block_indent(context.config), context.config)
2558 .sub_width(shape.rhs_overhead(context.config))?;
2559 let new_rhs = expr.rewrite(context, new_shape);
2560 let new_indent_str = &new_shape.indent.to_string_with_newline(context.config);
2562 match (orig_rhs, new_rhs) {
2563 (Some(ref orig_rhs), Some(ref new_rhs))
2564 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2567 Some(format!(" {}", orig_rhs))
2569 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2570 Some(format!("{}{}", new_indent_str, new_rhs))
2572 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2573 (None, None) => None,
2574 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2580 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2581 !next_line_rhs.contains('\n') || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2584 fn rewrite_expr_addrof(
2585 context: &RewriteContext,
2586 mutability: ast::Mutability,
2589 ) -> Option<String> {
2590 let operator_str = match mutability {
2591 ast::Mutability::Immutable => "&",
2592 ast::Mutability::Mutable => "&mut ",
2594 rewrite_unary_prefix(context, operator_str, expr, shape)
2598 fn to_expr(&self) -> Option<&ast::Expr>;
2599 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2602 impl ToExpr for ast::Expr {
2603 fn to_expr(&self) -> Option<&ast::Expr> {
2607 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2608 can_be_overflowed_expr(context, self, len)
2612 impl ToExpr for ast::Ty {
2613 fn to_expr(&self) -> Option<&ast::Expr> {
2617 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2618 can_be_overflowed_type(context, self, len)
2622 impl<'a> ToExpr for TuplePatField<'a> {
2623 fn to_expr(&self) -> Option<&ast::Expr> {
2627 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2628 can_be_overflowed_pat(context, self, len)
2632 impl<'a> ToExpr for ast::StructField {
2633 fn to_expr(&self) -> Option<&ast::Expr> {
2637 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
2642 impl<'a> ToExpr for MacroArg {
2643 fn to_expr(&self) -> Option<&ast::Expr> {
2645 MacroArg::Expr(ref expr) => Some(expr),
2650 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2652 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
2653 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
2654 MacroArg::Pat(..) => false,
2655 MacroArg::Item(..) => len == 1,
2660 impl ToExpr for ast::GenericParam {
2661 fn to_expr(&self) -> Option<&ast::Expr> {
2665 fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {