1 use std::borrow::Cow;
2 use std::cmp::min;
3
4 use itertools::Itertools;
5 use rustc_ast::token::{Delimiter, LitKind};
6 use rustc_ast::{ast, ptr, token};
7 use rustc_span::{BytePos, Span};
8
9 use crate::chains::rewrite_chain;
10 use crate::closures;
11 use crate::comment::{
12 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
13 rewrite_missing_comment, CharClasses, FindUncommented,
14 };
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version};
17 use crate::lists::{
18 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19 struct_lit_tactic, write_list, ListFormatting, Separator,
20 };
21 use crate::macros::{rewrite_macro, MacroPosition};
22 use crate::matches::rewrite_match;
23 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
24 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::string::{rewrite_string, StringFormat};
30 use crate::types::{rewrite_path, PathContext};
31 use crate::utils::{
32 colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with,
33 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
34 semicolon_for_expr, unicode_str_width, wrap_str,
35 };
36 use crate::vertical::rewrite_with_alignment;
37 use crate::visitor::FmtVisitor;
38
39 impl Rewrite for ast::Expr {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>40 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
42 }
43 }
44
45 #[derive(Copy, Clone, PartialEq)]
46 pub(crate) enum ExprType {
47 Statement,
48 SubExpression,
49 }
50
format_expr( expr: &ast::Expr, expr_type: ExprType, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>51 pub(crate) fn format_expr(
52 expr: &ast::Expr,
53 expr_type: ExprType,
54 context: &RewriteContext<'_>,
55 shape: Shape,
56 ) -> Option<String> {
57 skip_out_of_file_lines_range!(context, expr.span);
58
59 if contains_skip(&*expr.attrs) {
60 return Some(context.snippet(expr.span()).to_owned());
61 }
62 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
63 shape.sub_width(1)?
64 } else {
65 shape
66 };
67
68 let expr_rw = match expr.kind {
69 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
70 "",
71 expr_vec.iter(),
72 expr.span,
73 context,
74 shape,
75 choose_separator_tactic(context, expr.span),
76 None,
77 ),
78 ast::ExprKind::Lit(token_lit) => {
79 if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
80 Some(expr_rw)
81 } else {
82 if let LitKind::StrRaw(_) = token_lit.kind {
83 Some(context.snippet(expr.span).trim().into())
84 } else {
85 None
86 }
87 }
88 }
89 ast::ExprKind::Call(ref callee, ref args) => {
90 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
91 let callee_str = callee.rewrite(context, shape)?;
92 rewrite_call(context, &callee_str, args, inner_span, shape)
93 }
94 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
95 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
96 // FIXME: format comments between operands and operator
97 rewrite_all_pairs(expr, shape, context).or_else(|| {
98 rewrite_pair(
99 &**lhs,
100 &**rhs,
101 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
102 context,
103 shape,
104 context.config.binop_separator(),
105 )
106 })
107 }
108 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
109 ast::ExprKind::Struct(ref struct_expr) => {
110 let ast::StructExpr {
111 qself,
112 fields,
113 path,
114 rest,
115 } = &**struct_expr;
116 rewrite_struct_lit(
117 context,
118 path,
119 qself,
120 fields,
121 rest,
122 &expr.attrs,
123 expr.span,
124 shape,
125 )
126 }
127 ast::ExprKind::Tup(ref items) => {
128 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
129 }
130 ast::ExprKind::Let(..) => None,
131 ast::ExprKind::If(..)
132 | ast::ExprKind::ForLoop(..)
133 | ast::ExprKind::Loop(..)
134 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
135 .and_then(|control_flow| control_flow.rewrite(context, shape)),
136 ast::ExprKind::ConstBlock(ref anon_const) => {
137 Some(format!("const {}", anon_const.rewrite(context, shape)?))
138 }
139 ast::ExprKind::Block(ref block, opt_label) => {
140 match expr_type {
141 ExprType::Statement => {
142 if is_unsafe_block(block) {
143 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
144 } else if let rw @ Some(_) =
145 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
146 {
147 // Rewrite block without trying to put it in a single line.
148 rw
149 } else {
150 let prefix = block_prefix(context, block, shape)?;
151
152 rewrite_block_with_visitor(
153 context,
154 &prefix,
155 block,
156 Some(&expr.attrs),
157 opt_label,
158 shape,
159 true,
160 )
161 }
162 }
163 ExprType::SubExpression => {
164 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
165 }
166 }
167 }
168 ast::ExprKind::Match(ref cond, ref arms) => {
169 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
170 }
171 ast::ExprKind::Path(ref qself, ref path) => {
172 rewrite_path(context, PathContext::Expr, qself, path, shape)
173 }
174 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
175 rewrite_assignment(context, lhs, rhs, None, shape)
176 }
177 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
178 rewrite_assignment(context, lhs, rhs, Some(op), shape)
179 }
180 ast::ExprKind::Continue(ref opt_label) => {
181 let id_str = match *opt_label {
182 Some(label) => format!(" {}", label.ident),
183 None => String::new(),
184 };
185 Some(format!("continue{}", id_str))
186 }
187 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
188 let id_str = match *opt_label {
189 Some(label) => format!(" {}", label.ident),
190 None => String::new(),
191 };
192
193 if let Some(ref expr) = *opt_expr {
194 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
195 } else {
196 Some(format!("break{}", id_str))
197 }
198 }
199 ast::ExprKind::Yield(ref opt_expr) => {
200 if let Some(ref expr) = *opt_expr {
201 rewrite_unary_prefix(context, "yield ", &**expr, shape)
202 } else {
203 Some("yield".to_string())
204 }
205 }
206 ast::ExprKind::Closure(ref cl) => closures::rewrite_closure(
207 &cl.binder,
208 cl.constness,
209 cl.capture_clause,
210 &cl.asyncness,
211 cl.movability,
212 &cl.fn_decl,
213 &cl.body,
214 expr.span,
215 context,
216 shape,
217 ),
218 ast::ExprKind::Try(..)
219 | ast::ExprKind::Field(..)
220 | ast::ExprKind::MethodCall(..)
221 | ast::ExprKind::Await(_, _) => rewrite_chain(expr, context, shape),
222 ast::ExprKind::MacCall(ref mac) => {
223 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
224 wrap_str(
225 context.snippet(expr.span).to_owned(),
226 context.config.max_width(),
227 shape,
228 )
229 })
230 }
231 ast::ExprKind::Ret(None) => Some("return".to_owned()),
232 ast::ExprKind::Ret(Some(ref expr)) => {
233 rewrite_unary_prefix(context, "return ", &**expr, shape)
234 }
235 ast::ExprKind::Become(ref expr) => rewrite_unary_prefix(context, "become ", &**expr, shape),
236 ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
237 ast::ExprKind::Yeet(Some(ref expr)) => {
238 rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
239 }
240 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
241 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
242 }
243 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
244 &**expr,
245 &**ty,
246 PairParts::infix(" as "),
247 context,
248 shape,
249 SeparatorPlace::Front,
250 ),
251 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
252 &**expr,
253 &**ty,
254 PairParts::infix(": "),
255 context,
256 shape,
257 SeparatorPlace::Back,
258 ),
259 ast::ExprKind::Index(ref expr, ref index) => {
260 rewrite_index(&**expr, &**index, context, shape)
261 }
262 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
263 &**expr,
264 &*repeats.value,
265 PairParts::new("[", "; ", "]"),
266 context,
267 shape,
268 SeparatorPlace::Back,
269 ),
270 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
271 let delim = match limits {
272 ast::RangeLimits::HalfOpen => "..",
273 ast::RangeLimits::Closed => "..=",
274 };
275
276 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
277 match lhs.kind {
278 ast::ExprKind::Lit(token_lit) => match token_lit.kind {
279 token::LitKind::Float if token_lit.suffix.is_none() => {
280 context.snippet(lhs.span).ends_with('.')
281 }
282 _ => false,
283 },
284 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
285 _ => false,
286 }
287 }
288
289 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
290 // Don't format `.. ..` into `....`, which is invalid.
291 //
292 // This check is unnecessary for `lhs`, because a range
293 // starting from another range needs parentheses as `(x ..) ..`
294 // (`x .. ..` is a range from `x` to `..`).
295 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
296 }
297
298 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
299 let space_if = |b: bool| if b { " " } else { "" };
300
301 format!(
302 "{}{}{}",
303 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
304 delim,
305 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
306 )
307 };
308
309 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
310 (Some(lhs), Some(rhs)) => {
311 let sp_delim = if context.config.spaces_around_ranges() {
312 format!(" {} ", delim)
313 } else {
314 default_sp_delim(Some(lhs), Some(rhs))
315 };
316 rewrite_pair(
317 &*lhs,
318 &*rhs,
319 PairParts::infix(&sp_delim),
320 context,
321 shape,
322 context.config.binop_separator(),
323 )
324 }
325 (None, Some(rhs)) => {
326 let sp_delim = if context.config.spaces_around_ranges() {
327 format!("{} ", delim)
328 } else {
329 default_sp_delim(None, Some(rhs))
330 };
331 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
332 }
333 (Some(lhs), None) => {
334 let sp_delim = if context.config.spaces_around_ranges() {
335 format!(" {}", delim)
336 } else {
337 default_sp_delim(Some(lhs), None)
338 };
339 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
340 }
341 (None, None) => Some(delim.to_owned()),
342 }
343 }
344 // We do not format these expressions yet, but they should still
345 // satisfy our width restrictions.
346 // Style Guide RFC for InlineAsm variant pending
347 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
348 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
349 ast::ExprKind::TryBlock(ref block) => {
350 if let rw @ Some(_) =
351 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
352 {
353 rw
354 } else {
355 // 9 = `try `
356 let budget = shape.width.saturating_sub(9);
357 Some(format!(
358 "{}{}",
359 "try ",
360 rewrite_block(
361 block,
362 Some(&expr.attrs),
363 None,
364 context,
365 Shape::legacy(budget, shape.indent)
366 )?
367 ))
368 }
369 }
370 ast::ExprKind::Async(capture_by, ref block) => {
371 let mover = if capture_by == ast::CaptureBy::Value {
372 "move "
373 } else {
374 ""
375 };
376 if let rw @ Some(_) = rewrite_single_line_block(
377 context,
378 format!("{}{}", "async ", mover).as_str(),
379 block,
380 Some(&expr.attrs),
381 None,
382 shape,
383 ) {
384 rw
385 } else {
386 // 6 = `async `
387 let budget = shape.width.saturating_sub(6);
388 Some(format!(
389 "{}{}{}",
390 "async ",
391 mover,
392 rewrite_block(
393 block,
394 Some(&expr.attrs),
395 None,
396 context,
397 Shape::legacy(budget, shape.indent)
398 )?
399 ))
400 }
401 }
402 ast::ExprKind::Underscore => Some("_".to_owned()),
403 ast::ExprKind::FormatArgs(..)
404 | ast::ExprKind::IncludedBytes(..)
405 | ast::ExprKind::OffsetOf(..) => {
406 // These do not occur in the AST because macros aren't expanded.
407 unreachable!()
408 }
409 ast::ExprKind::Err => None,
410 };
411
412 expr_rw
413 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
414 .and_then(|expr_str| {
415 let attrs = outer_attributes(&expr.attrs);
416 let attrs_str = attrs.rewrite(context, shape)?;
417 let span = mk_sp(
418 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
419 expr.span.lo(),
420 );
421 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
422 })
423 }
424
rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>( name: &'a str, exprs: impl Iterator<Item = &'a T>, span: Span, context: &'a RewriteContext<'_>, shape: Shape, force_separator_tactic: Option<SeparatorTactic>, delim_token: Option<Delimiter>, ) -> Option<String>425 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
426 name: &'a str,
427 exprs: impl Iterator<Item = &'a T>,
428 span: Span,
429 context: &'a RewriteContext<'_>,
430 shape: Shape,
431 force_separator_tactic: Option<SeparatorTactic>,
432 delim_token: Option<Delimiter>,
433 ) -> Option<String> {
434 overflow::rewrite_with_square_brackets(
435 context,
436 name,
437 exprs,
438 shape,
439 span,
440 force_separator_tactic,
441 delim_token,
442 )
443 }
444
rewrite_empty_block( context: &RewriteContext<'_>, block: &ast::Block, attrs: Option<&[ast::Attribute]>, label: Option<ast::Label>, prefix: &str, shape: Shape, ) -> Option<String>445 fn rewrite_empty_block(
446 context: &RewriteContext<'_>,
447 block: &ast::Block,
448 attrs: Option<&[ast::Attribute]>,
449 label: Option<ast::Label>,
450 prefix: &str,
451 shape: Shape,
452 ) -> Option<String> {
453 if block_has_statements(block) {
454 return None;
455 }
456
457 let label_str = rewrite_label(label);
458 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
459 return None;
460 }
461
462 if !block_contains_comment(context, block) && shape.width >= 2 {
463 return Some(format!("{}{}{{}}", prefix, label_str));
464 }
465
466 // If a block contains only a single-line comment, then leave it on one line.
467 let user_str = context.snippet(block.span);
468 let user_str = user_str.trim();
469 if user_str.starts_with('{') && user_str.ends_with('}') {
470 let comment_str = user_str[1..user_str.len() - 1].trim();
471 if block.stmts.is_empty()
472 && !comment_str.contains('\n')
473 && !comment_str.starts_with("//")
474 && comment_str.len() + 4 <= shape.width
475 {
476 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
477 }
478 }
479
480 None
481 }
482
block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String>483 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
484 Some(match block.rules {
485 ast::BlockCheckMode::Unsafe(..) => {
486 let snippet = context.snippet(block.span);
487 let open_pos = snippet.find_uncommented("{")?;
488 // Extract comment between unsafe and block start.
489 let trimmed = &snippet[6..open_pos].trim();
490
491 if !trimmed.is_empty() {
492 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
493 let budget = shape.width.checked_sub(9)?;
494 format!(
495 "unsafe {} ",
496 rewrite_comment(
497 trimmed,
498 true,
499 Shape::legacy(budget, shape.indent + 7),
500 context.config,
501 )?
502 )
503 } else {
504 "unsafe ".to_owned()
505 }
506 }
507 ast::BlockCheckMode::Default => String::new(),
508 })
509 }
510
rewrite_single_line_block( context: &RewriteContext<'_>, prefix: &str, block: &ast::Block, attrs: Option<&[ast::Attribute]>, label: Option<ast::Label>, shape: Shape, ) -> Option<String>511 fn rewrite_single_line_block(
512 context: &RewriteContext<'_>,
513 prefix: &str,
514 block: &ast::Block,
515 attrs: Option<&[ast::Attribute]>,
516 label: Option<ast::Label>,
517 shape: Shape,
518 ) -> Option<String> {
519 if is_simple_block(context, block, attrs) {
520 let expr_shape = shape.offset_left(last_line_width(prefix))?;
521 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
522 let label_str = rewrite_label(label);
523 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
524 if result.len() <= shape.width && !result.contains('\n') {
525 return Some(result);
526 }
527 }
528 None
529 }
530
rewrite_block_with_visitor( context: &RewriteContext<'_>, prefix: &str, block: &ast::Block, attrs: Option<&[ast::Attribute]>, label: Option<ast::Label>, shape: Shape, has_braces: bool, ) -> Option<String>531 pub(crate) fn rewrite_block_with_visitor(
532 context: &RewriteContext<'_>,
533 prefix: &str,
534 block: &ast::Block,
535 attrs: Option<&[ast::Attribute]>,
536 label: Option<ast::Label>,
537 shape: Shape,
538 has_braces: bool,
539 ) -> Option<String> {
540 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
541 return rw;
542 }
543
544 let mut visitor = FmtVisitor::from_context(context);
545 visitor.block_indent = shape.indent;
546 visitor.is_if_else_block = context.is_if_else_block();
547 match (block.rules, label) {
548 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
549 let snippet = context.snippet(block.span);
550 let open_pos = snippet.find_uncommented("{")?;
551 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
552 }
553 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
554 }
555
556 let inner_attrs = attrs.map(inner_attributes);
557 let label_str = rewrite_label(label);
558 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
559 let visitor_context = visitor.get_context();
560 context
561 .skipped_range
562 .borrow_mut()
563 .append(&mut visitor_context.skipped_range.borrow_mut());
564 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
565 }
566
567 impl Rewrite for ast::Block {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>568 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
569 rewrite_block(self, None, None, context, shape)
570 }
571 }
572
rewrite_block( block: &ast::Block, attrs: Option<&[ast::Attribute]>, label: Option<ast::Label>, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>573 fn rewrite_block(
574 block: &ast::Block,
575 attrs: Option<&[ast::Attribute]>,
576 label: Option<ast::Label>,
577 context: &RewriteContext<'_>,
578 shape: Shape,
579 ) -> Option<String> {
580 rewrite_block_inner(block, attrs, label, true, context, shape)
581 }
582
rewrite_block_inner( block: &ast::Block, attrs: Option<&[ast::Attribute]>, label: Option<ast::Label>, allow_single_line: bool, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>583 fn rewrite_block_inner(
584 block: &ast::Block,
585 attrs: Option<&[ast::Attribute]>,
586 label: Option<ast::Label>,
587 allow_single_line: bool,
588 context: &RewriteContext<'_>,
589 shape: Shape,
590 ) -> Option<String> {
591 let prefix = block_prefix(context, block, shape)?;
592
593 // shape.width is used only for the single line case: either the empty block `{}`,
594 // or an unsafe expression `unsafe { e }`.
595 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
596 return rw;
597 }
598
599 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
600 if let Some(ref result_str) = result {
601 if allow_single_line && result_str.lines().count() <= 3 {
602 if let rw @ Some(_) =
603 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
604 {
605 return rw;
606 }
607 }
608 }
609
610 result
611 }
612
613 /// Rewrite the divergent block of a `let-else` statement.
rewrite_let_else_block( block: &ast::Block, allow_single_line: bool, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>614 pub(crate) fn rewrite_let_else_block(
615 block: &ast::Block,
616 allow_single_line: bool,
617 context: &RewriteContext<'_>,
618 shape: Shape,
619 ) -> Option<String> {
620 rewrite_block_inner(block, None, None, allow_single_line, context, shape)
621 }
622
623 // Rewrite condition if the given expression has one.
rewrite_cond( context: &RewriteContext<'_>, expr: &ast::Expr, shape: Shape, ) -> Option<String>624 pub(crate) fn rewrite_cond(
625 context: &RewriteContext<'_>,
626 expr: &ast::Expr,
627 shape: Shape,
628 ) -> Option<String> {
629 match expr.kind {
630 ast::ExprKind::Match(ref cond, _) => {
631 // `match `cond` {`
632 let cond_shape = match context.config.indent_style() {
633 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
634 IndentStyle::Block => shape.offset_left(8)?,
635 };
636 cond.rewrite(context, cond_shape)
637 }
638 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
639 let alt_block_sep =
640 String::from("\n") + &shape.indent.block_only().to_string(context.config);
641 control_flow
642 .rewrite_cond(context, shape, &alt_block_sep)
643 .map(|rw| rw.0)
644 }),
645 }
646 }
647
648 // Abstraction over control flow expressions
649 #[derive(Debug)]
650 struct ControlFlow<'a> {
651 cond: Option<&'a ast::Expr>,
652 block: &'a ast::Block,
653 else_block: Option<&'a ast::Expr>,
654 label: Option<ast::Label>,
655 pat: Option<&'a ast::Pat>,
656 keyword: &'a str,
657 matcher: &'a str,
658 connector: &'a str,
659 allow_single_line: bool,
660 // HACK: `true` if this is an `if` expression in an `else if`.
661 nested_if: bool,
662 span: Span,
663 }
664
extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr)665 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
666 match expr.kind {
667 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
668 _ => (None, expr),
669 }
670 }
671
672 // FIXME: Refactor this.
to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>>673 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
674 match expr.kind {
675 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
676 let (pat, cond) = extract_pats_and_cond(cond);
677 Some(ControlFlow::new_if(
678 cond,
679 pat,
680 if_block,
681 else_block.as_ref().map(|e| &**e),
682 expr_type == ExprType::SubExpression,
683 false,
684 expr.span,
685 ))
686 }
687 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
688 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
689 }
690 ast::ExprKind::Loop(ref block, label, _) => {
691 Some(ControlFlow::new_loop(block, label, expr.span))
692 }
693 ast::ExprKind::While(ref cond, ref block, label) => {
694 let (pat, cond) = extract_pats_and_cond(cond);
695 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
696 }
697 _ => None,
698 }
699 }
700
choose_matcher(pat: Option<&ast::Pat>) -> &'static str701 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
702 pat.map_or("", |_| "let")
703 }
704
705 impl<'a> ControlFlow<'a> {
new_if( cond: &'a ast::Expr, pat: Option<&'a ast::Pat>, block: &'a ast::Block, else_block: Option<&'a ast::Expr>, allow_single_line: bool, nested_if: bool, span: Span, ) -> ControlFlow<'a>706 fn new_if(
707 cond: &'a ast::Expr,
708 pat: Option<&'a ast::Pat>,
709 block: &'a ast::Block,
710 else_block: Option<&'a ast::Expr>,
711 allow_single_line: bool,
712 nested_if: bool,
713 span: Span,
714 ) -> ControlFlow<'a> {
715 let matcher = choose_matcher(pat);
716 ControlFlow {
717 cond: Some(cond),
718 block,
719 else_block,
720 label: None,
721 pat,
722 keyword: "if",
723 matcher,
724 connector: " =",
725 allow_single_line,
726 nested_if,
727 span,
728 }
729 }
730
new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a>731 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
732 ControlFlow {
733 cond: None,
734 block,
735 else_block: None,
736 label,
737 pat: None,
738 keyword: "loop",
739 matcher: "",
740 connector: "",
741 allow_single_line: false,
742 nested_if: false,
743 span,
744 }
745 }
746
new_while( pat: Option<&'a ast::Pat>, cond: &'a ast::Expr, block: &'a ast::Block, label: Option<ast::Label>, span: Span, ) -> ControlFlow<'a>747 fn new_while(
748 pat: Option<&'a ast::Pat>,
749 cond: &'a ast::Expr,
750 block: &'a ast::Block,
751 label: Option<ast::Label>,
752 span: Span,
753 ) -> ControlFlow<'a> {
754 let matcher = choose_matcher(pat);
755 ControlFlow {
756 cond: Some(cond),
757 block,
758 else_block: None,
759 label,
760 pat,
761 keyword: "while",
762 matcher,
763 connector: " =",
764 allow_single_line: false,
765 nested_if: false,
766 span,
767 }
768 }
769
new_for( pat: &'a ast::Pat, cond: &'a ast::Expr, block: &'a ast::Block, label: Option<ast::Label>, span: Span, ) -> ControlFlow<'a>770 fn new_for(
771 pat: &'a ast::Pat,
772 cond: &'a ast::Expr,
773 block: &'a ast::Block,
774 label: Option<ast::Label>,
775 span: Span,
776 ) -> ControlFlow<'a> {
777 ControlFlow {
778 cond: Some(cond),
779 block,
780 else_block: None,
781 label,
782 pat: Some(pat),
783 keyword: "for",
784 matcher: "",
785 connector: " in",
786 allow_single_line: false,
787 nested_if: false,
788 span,
789 }
790 }
791
rewrite_single_line( &self, pat_expr_str: &str, context: &RewriteContext<'_>, width: usize, ) -> Option<String>792 fn rewrite_single_line(
793 &self,
794 pat_expr_str: &str,
795 context: &RewriteContext<'_>,
796 width: usize,
797 ) -> Option<String> {
798 assert!(self.allow_single_line);
799 let else_block = self.else_block?;
800 let fixed_cost = self.keyword.len() + " { } else { }".len();
801
802 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
803 if !is_simple_block(context, self.block, None)
804 || !is_simple_block(context, else_node, None)
805 || pat_expr_str.contains('\n')
806 {
807 return None;
808 }
809
810 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
811 let expr = &self.block.stmts[0];
812 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
813
814 let new_width = new_width.checked_sub(if_str.len())?;
815 let else_expr = &else_node.stmts[0];
816 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
817
818 if if_str.contains('\n') || else_str.contains('\n') {
819 return None;
820 }
821
822 let result = format!(
823 "{} {} {{ {} }} else {{ {} }}",
824 self.keyword, pat_expr_str, if_str, else_str
825 );
826
827 if result.len() <= width {
828 return Some(result);
829 }
830 }
831
832 None
833 }
834 }
835
836 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
837 /// shape's indent.
last_line_offsetted(start_column: usize, pat_str: &str) -> bool838 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
839 let mut leading_whitespaces = 0;
840 for c in pat_str.chars().rev() {
841 match c {
842 '\n' => break,
843 _ if c.is_whitespace() => leading_whitespaces += 1,
844 _ => leading_whitespaces = 0,
845 }
846 }
847 leading_whitespaces > start_column
848 }
849
850 impl<'a> ControlFlow<'a> {
rewrite_pat_expr( &self, context: &RewriteContext<'_>, expr: &ast::Expr, shape: Shape, offset: usize, ) -> Option<String>851 fn rewrite_pat_expr(
852 &self,
853 context: &RewriteContext<'_>,
854 expr: &ast::Expr,
855 shape: Shape,
856 offset: usize,
857 ) -> Option<String> {
858 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
859
860 let cond_shape = shape.offset_left(offset)?;
861 if let Some(pat) = self.pat {
862 let matcher = if self.matcher.is_empty() {
863 self.matcher.to_owned()
864 } else {
865 format!("{} ", self.matcher)
866 };
867 let pat_shape = cond_shape
868 .offset_left(matcher.len())?
869 .sub_width(self.connector.len())?;
870 let pat_string = pat.rewrite(context, pat_shape)?;
871 let comments_lo = context
872 .snippet_provider
873 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
874 let comments_span = mk_sp(comments_lo, expr.span.lo());
875 return rewrite_assign_rhs_with_comments(
876 context,
877 &format!("{}{}{}", matcher, pat_string, self.connector),
878 expr,
879 cond_shape,
880 &RhsAssignKind::Expr(&expr.kind, expr.span),
881 RhsTactics::Default,
882 comments_span,
883 true,
884 );
885 }
886
887 let expr_rw = expr.rewrite(context, cond_shape);
888 // The expression may (partially) fit on the current line.
889 // We do not allow splitting between `if` and condition.
890 if self.keyword == "if" || expr_rw.is_some() {
891 return expr_rw;
892 }
893
894 // The expression won't fit on the current line, jump to next.
895 let nested_shape = shape
896 .block_indent(context.config.tab_spaces())
897 .with_max_width(context.config);
898 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
899 expr.rewrite(context, nested_shape)
900 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
901 }
902
rewrite_cond( &self, context: &RewriteContext<'_>, shape: Shape, alt_block_sep: &str, ) -> Option<(String, usize)>903 fn rewrite_cond(
904 &self,
905 context: &RewriteContext<'_>,
906 shape: Shape,
907 alt_block_sep: &str,
908 ) -> Option<(String, usize)> {
909 // Do not take the rhs overhead from the upper expressions into account
910 // when rewriting pattern.
911 let new_width = context.budget(shape.used_width());
912 let fresh_shape = Shape {
913 width: new_width,
914 ..shape
915 };
916 let constr_shape = if self.nested_if {
917 // We are part of an if-elseif-else chain. Our constraints are tightened.
918 // 7 = "} else " .len()
919 fresh_shape.offset_left(7)?
920 } else {
921 fresh_shape
922 };
923
924 let label_string = rewrite_label(self.label);
925 // 1 = space after keyword.
926 let offset = self.keyword.len() + label_string.len() + 1;
927
928 let pat_expr_string = match self.cond {
929 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
930 None => String::new(),
931 };
932
933 let brace_overhead =
934 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
935 // 2 = ` {`
936 2
937 } else {
938 0
939 };
940 let one_line_budget = context
941 .config
942 .max_width()
943 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
944 let force_newline_brace = (pat_expr_string.contains('\n')
945 || pat_expr_string.len() > one_line_budget)
946 && (!last_line_extendable(&pat_expr_string)
947 || last_line_offsetted(shape.used_width(), &pat_expr_string));
948
949 // Try to format if-else on single line.
950 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
951 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
952
953 if let Some(cond_str) = trial {
954 if cond_str.len() <= context.config.single_line_if_else_max_width() {
955 return Some((cond_str, 0));
956 }
957 }
958 }
959
960 let cond_span = if let Some(cond) = self.cond {
961 cond.span
962 } else {
963 mk_sp(self.block.span.lo(), self.block.span.lo())
964 };
965
966 // `for event in event`
967 // Do not include label in the span.
968 let lo = self
969 .label
970 .map_or(self.span.lo(), |label| label.ident.span.hi());
971 let between_kwd_cond = mk_sp(
972 context
973 .snippet_provider
974 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
975 if self.pat.is_none() {
976 cond_span.lo()
977 } else if self.matcher.is_empty() {
978 self.pat.unwrap().span.lo()
979 } else {
980 context
981 .snippet_provider
982 .span_before(self.span, self.matcher.trim())
983 },
984 );
985
986 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
987
988 let after_cond_comment =
989 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
990
991 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
992 ""
993 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
994 || force_newline_brace
995 {
996 alt_block_sep
997 } else {
998 " "
999 };
1000
1001 let used_width = if pat_expr_string.contains('\n') {
1002 last_line_width(&pat_expr_string)
1003 } else {
1004 // 2 = spaces after keyword and condition.
1005 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1006 };
1007
1008 Some((
1009 format!(
1010 "{}{}{}{}{}",
1011 label_string,
1012 self.keyword,
1013 between_kwd_cond_comment.as_ref().map_or(
1014 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1015 ""
1016 } else {
1017 " "
1018 },
1019 |s| &**s,
1020 ),
1021 pat_expr_string,
1022 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1023 ),
1024 used_width,
1025 ))
1026 }
1027 }
1028
1029 /// Rewrite the `else` keyword with surrounding comments.
1030 ///
1031 /// force_newline_else: whether or not to rewrite the `else` keyword on a newline.
1032 /// is_last: true if this is an `else` and `false` if this is an `else if` block.
1033 /// context: rewrite context
1034 /// span: Span between the end of the last expression and the start of the else block,
1035 /// which contains the `else` keyword
1036 /// shape: Shape
rewrite_else_kw_with_comments( force_newline_else: bool, is_last: bool, context: &RewriteContext<'_>, span: Span, shape: Shape, ) -> String1037 pub(crate) fn rewrite_else_kw_with_comments(
1038 force_newline_else: bool,
1039 is_last: bool,
1040 context: &RewriteContext<'_>,
1041 span: Span,
1042 shape: Shape,
1043 ) -> String {
1044 let else_kw_lo = context.snippet_provider.span_before(span, "else");
1045 let before_else_kw = mk_sp(span.lo(), else_kw_lo);
1046 let before_else_kw_comment = extract_comment(before_else_kw, context, shape);
1047
1048 let else_kw_hi = context.snippet_provider.span_after(span, "else");
1049 let after_else_kw = mk_sp(else_kw_hi, span.hi());
1050 let after_else_kw_comment = extract_comment(after_else_kw, context, shape);
1051
1052 let newline_sep = &shape.indent.to_string_with_newline(context.config);
1053 let before_sep = match context.config.control_brace_style() {
1054 _ if force_newline_else => newline_sep.as_ref(),
1055 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1056 newline_sep.as_ref()
1057 }
1058 ControlBraceStyle::AlwaysSameLine => " ",
1059 };
1060 let after_sep = match context.config.control_brace_style() {
1061 ControlBraceStyle::AlwaysNextLine if is_last => newline_sep.as_ref(),
1062 _ => " ",
1063 };
1064
1065 format!(
1066 "{}else{}",
1067 before_else_kw_comment.as_ref().map_or(before_sep, |s| &**s),
1068 after_else_kw_comment.as_ref().map_or(after_sep, |s| &**s),
1069 )
1070 }
1071
1072 impl<'a> Rewrite for ControlFlow<'a> {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>1073 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1074 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1075
1076 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1077 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1078 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1079 if used_width == 0 {
1080 return Some(cond_str);
1081 }
1082
1083 let block_width = shape.width.saturating_sub(used_width);
1084 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1085 // we should avoid the single line case.
1086 let block_width = if self.else_block.is_some() || self.nested_if {
1087 min(1, block_width)
1088 } else {
1089 block_width
1090 };
1091 let block_shape = Shape {
1092 width: block_width,
1093 ..shape
1094 };
1095 let block_str = {
1096 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1097 let result =
1098 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1099 context.is_if_else_block.replace(old_val);
1100 result?
1101 };
1102
1103 let mut result = format!("{}{}", cond_str, block_str);
1104
1105 if let Some(else_block) = self.else_block {
1106 let shape = Shape::indented(shape.indent, context.config);
1107 let mut last_in_chain = false;
1108 let rewrite = match else_block.kind {
1109 // If the else expression is another if-else expression, prevent it
1110 // from being formatted on a single line.
1111 // Note how we're passing the original shape, as the
1112 // cost of "else" should not cascade.
1113 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1114 let (pats, cond) = extract_pats_and_cond(cond);
1115 ControlFlow::new_if(
1116 cond,
1117 pats,
1118 if_block,
1119 next_else_block.as_ref().map(|e| &**e),
1120 false,
1121 true,
1122 mk_sp(else_block.span.lo(), self.span.hi()),
1123 )
1124 .rewrite(context, shape)
1125 }
1126 _ => {
1127 last_in_chain = true;
1128 // When rewriting a block, the width is only used for single line
1129 // blocks, passing 1 lets us avoid that.
1130 let else_shape = Shape {
1131 width: min(1, shape.width),
1132 ..shape
1133 };
1134 format_expr(else_block, ExprType::Statement, context, else_shape)
1135 }
1136 };
1137
1138 let else_kw = rewrite_else_kw_with_comments(
1139 false,
1140 last_in_chain,
1141 context,
1142 self.block.span.between(else_block.span),
1143 shape,
1144 );
1145 result.push_str(&else_kw);
1146 result.push_str(&rewrite?);
1147 }
1148
1149 Some(result)
1150 }
1151 }
1152
rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str>1153 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1154 match opt_label {
1155 Some(label) => Cow::from(format!("{}: ", label.ident)),
1156 None => Cow::from(""),
1157 }
1158 }
1159
extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String>1160 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1161 match rewrite_missing_comment(span, shape, context) {
1162 Some(ref comment) if !comment.is_empty() => Some(format!(
1163 "{indent}{}{indent}",
1164 comment,
1165 indent = shape.indent.to_string_with_newline(context.config)
1166 )),
1167 _ => None,
1168 }
1169 }
1170
block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool1171 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1172 contains_comment(context.snippet(block.span))
1173 }
1174
1175 // Checks that a block contains no statements, an expression and no comments or
1176 // attributes.
1177 // FIXME: incorrectly returns false when comment is contained completely within
1178 // the expression.
is_simple_block( context: &RewriteContext<'_>, block: &ast::Block, attrs: Option<&[ast::Attribute]>, ) -> bool1179 pub(crate) fn is_simple_block(
1180 context: &RewriteContext<'_>,
1181 block: &ast::Block,
1182 attrs: Option<&[ast::Attribute]>,
1183 ) -> bool {
1184 block.stmts.len() == 1
1185 && stmt_is_expr(&block.stmts[0])
1186 && !block_contains_comment(context, block)
1187 && attrs.map_or(true, |a| a.is_empty())
1188 }
1189
1190 /// Checks whether a block contains at most one statement or expression, and no
1191 /// comments or attributes.
is_simple_block_stmt( context: &RewriteContext<'_>, block: &ast::Block, attrs: Option<&[ast::Attribute]>, ) -> bool1192 pub(crate) fn is_simple_block_stmt(
1193 context: &RewriteContext<'_>,
1194 block: &ast::Block,
1195 attrs: Option<&[ast::Attribute]>,
1196 ) -> bool {
1197 block.stmts.len() <= 1
1198 && !block_contains_comment(context, block)
1199 && attrs.map_or(true, |a| a.is_empty())
1200 }
1201
block_has_statements(block: &ast::Block) -> bool1202 fn block_has_statements(block: &ast::Block) -> bool {
1203 block
1204 .stmts
1205 .iter()
1206 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1207 }
1208
1209 /// Checks whether a block contains no statements, expressions, comments, or
1210 /// inner attributes.
is_empty_block( context: &RewriteContext<'_>, block: &ast::Block, attrs: Option<&[ast::Attribute]>, ) -> bool1211 pub(crate) fn is_empty_block(
1212 context: &RewriteContext<'_>,
1213 block: &ast::Block,
1214 attrs: Option<&[ast::Attribute]>,
1215 ) -> bool {
1216 !block_has_statements(block)
1217 && !block_contains_comment(context, block)
1218 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1219 }
1220
stmt_is_expr(stmt: &ast::Stmt) -> bool1221 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1222 matches!(stmt.kind, ast::StmtKind::Expr(..))
1223 }
1224
is_unsafe_block(block: &ast::Block) -> bool1225 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1226 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1227 }
1228
rewrite_literal( context: &RewriteContext<'_>, token_lit: token::Lit, span: Span, shape: Shape, ) -> Option<String>1229 pub(crate) fn rewrite_literal(
1230 context: &RewriteContext<'_>,
1231 token_lit: token::Lit,
1232 span: Span,
1233 shape: Shape,
1234 ) -> Option<String> {
1235 match token_lit.kind {
1236 token::LitKind::Str => rewrite_string_lit(context, span, shape),
1237 token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape),
1238 _ => wrap_str(
1239 context.snippet(span).to_owned(),
1240 context.config.max_width(),
1241 shape,
1242 ),
1243 }
1244 }
1245
rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String>1246 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1247 let string_lit = context.snippet(span);
1248
1249 if !context.config.format_strings() {
1250 if string_lit
1251 .lines()
1252 .dropping_back(1)
1253 .all(|line| line.ends_with('\\'))
1254 && context.config.version() == Version::Two
1255 {
1256 return Some(string_lit.to_owned());
1257 } else {
1258 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1259 }
1260 }
1261
1262 // Remove the quote characters.
1263 let str_lit = &string_lit[1..string_lit.len() - 1];
1264
1265 rewrite_string(
1266 str_lit,
1267 &StringFormat::new(shape.visual_indent(0), context.config),
1268 shape.width.saturating_sub(2),
1269 )
1270 }
1271
rewrite_int_lit( context: &RewriteContext<'_>, token_lit: token::Lit, span: Span, shape: Shape, ) -> Option<String>1272 fn rewrite_int_lit(
1273 context: &RewriteContext<'_>,
1274 token_lit: token::Lit,
1275 span: Span,
1276 shape: Shape,
1277 ) -> Option<String> {
1278 let symbol = token_lit.symbol.as_str();
1279
1280 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1281 let hex_lit = match context.config.hex_literal_case() {
1282 HexLiteralCase::Preserve => None,
1283 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1284 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1285 };
1286 if let Some(hex_lit) = hex_lit {
1287 return wrap_str(
1288 format!(
1289 "0x{}{}",
1290 hex_lit,
1291 token_lit.suffix.map_or(String::new(), |s| s.to_string())
1292 ),
1293 context.config.max_width(),
1294 shape,
1295 );
1296 }
1297 }
1298
1299 wrap_str(
1300 context.snippet(span).to_owned(),
1301 context.config.max_width(),
1302 shape,
1303 )
1304 }
1305
choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic>1306 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1307 if context.inside_macro() {
1308 if span_ends_with_comma(context, span) {
1309 Some(SeparatorTactic::Always)
1310 } else {
1311 Some(SeparatorTactic::Never)
1312 }
1313 } else {
1314 None
1315 }
1316 }
1317
rewrite_call( context: &RewriteContext<'_>, callee: &str, args: &[ptr::P<ast::Expr>], span: Span, shape: Shape, ) -> Option<String>1318 pub(crate) fn rewrite_call(
1319 context: &RewriteContext<'_>,
1320 callee: &str,
1321 args: &[ptr::P<ast::Expr>],
1322 span: Span,
1323 shape: Shape,
1324 ) -> Option<String> {
1325 overflow::rewrite_with_parens(
1326 context,
1327 callee,
1328 args.iter(),
1329 shape,
1330 span,
1331 context.config.fn_call_width(),
1332 choose_separator_tactic(context, span),
1333 )
1334 }
1335
is_simple_expr(expr: &ast::Expr) -> bool1336 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1337 match expr.kind {
1338 ast::ExprKind::Lit(..) => true,
1339 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1340 ast::ExprKind::AddrOf(_, _, ref expr)
1341 | ast::ExprKind::Cast(ref expr, _)
1342 | ast::ExprKind::Field(ref expr, _)
1343 | ast::ExprKind::Try(ref expr)
1344 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1345 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1346 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1347 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1348 }
1349 _ => false,
1350 }
1351 }
1352
is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool1353 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1354 lists.iter().all(OverflowableItem::is_simple)
1355 }
1356
can_be_overflowed_expr( context: &RewriteContext<'_>, expr: &ast::Expr, args_len: usize, ) -> bool1357 pub(crate) fn can_be_overflowed_expr(
1358 context: &RewriteContext<'_>,
1359 expr: &ast::Expr,
1360 args_len: usize,
1361 ) -> bool {
1362 match expr.kind {
1363 _ if !expr.attrs.is_empty() => false,
1364 ast::ExprKind::Match(..) => {
1365 (context.use_block_indent() && args_len == 1)
1366 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1367 || context.config.overflow_delimited_expr()
1368 }
1369 ast::ExprKind::If(..)
1370 | ast::ExprKind::ForLoop(..)
1371 | ast::ExprKind::Loop(..)
1372 | ast::ExprKind::While(..) => {
1373 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1374 }
1375
1376 // Handle always block-like expressions
1377 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1378
1379 // Handle `[]` and `{}`-like expressions
1380 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1381 context.config.overflow_delimited_expr()
1382 || (context.use_block_indent() && args_len == 1)
1383 }
1384 ast::ExprKind::MacCall(ref mac) => {
1385 match (
1386 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim.to_token()),
1387 context.config.overflow_delimited_expr(),
1388 ) {
1389 (Some(ast::MacDelimiter::Bracket), true)
1390 | (Some(ast::MacDelimiter::Brace), true) => true,
1391 _ => context.use_block_indent() && args_len == 1,
1392 }
1393 }
1394
1395 // Handle parenthetical expressions
1396 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1397 context.use_block_indent() && args_len == 1
1398 }
1399
1400 // Handle unary-like expressions
1401 ast::ExprKind::AddrOf(_, _, ref expr)
1402 | ast::ExprKind::Try(ref expr)
1403 | ast::ExprKind::Unary(_, ref expr)
1404 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1405 _ => false,
1406 }
1407 }
1408
is_nested_call(expr: &ast::Expr) -> bool1409 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1410 match expr.kind {
1411 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1412 ast::ExprKind::AddrOf(_, _, ref expr)
1413 | ast::ExprKind::Try(ref expr)
1414 | ast::ExprKind::Unary(_, ref expr)
1415 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1416 _ => false,
1417 }
1418 }
1419
1420 /// Returns `true` if a function call or a method call represented by the given span ends with a
1421 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1422 /// comma from macro can potentially break the code.
span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool1423 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1424 let mut result: bool = Default::default();
1425 let mut prev_char: char = Default::default();
1426 let closing_delimiters = &[')', '}', ']'];
1427
1428 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1429 match c {
1430 _ if kind.is_comment() || c.is_whitespace() => continue,
1431 c if closing_delimiters.contains(&c) => {
1432 result &= !closing_delimiters.contains(&prev_char);
1433 }
1434 ',' => result = true,
1435 _ => result = false,
1436 }
1437 prev_char = c;
1438 }
1439
1440 result
1441 }
1442
rewrite_paren( context: &RewriteContext<'_>, mut subexpr: &ast::Expr, shape: Shape, mut span: Span, ) -> Option<String>1443 fn rewrite_paren(
1444 context: &RewriteContext<'_>,
1445 mut subexpr: &ast::Expr,
1446 shape: Shape,
1447 mut span: Span,
1448 ) -> Option<String> {
1449 debug!("rewrite_paren, shape: {:?}", shape);
1450
1451 // Extract comments within parens.
1452 let mut pre_span;
1453 let mut post_span;
1454 let mut pre_comment;
1455 let mut post_comment;
1456 let remove_nested_parens = context.config.remove_nested_parens();
1457 loop {
1458 // 1 = "(" or ")"
1459 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1460 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1461 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1462 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1463
1464 // Remove nested parens if there are no comments.
1465 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1466 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1467 span = subexpr.span;
1468 subexpr = subsubexpr;
1469 continue;
1470 }
1471 }
1472
1473 break;
1474 }
1475
1476 // 1 = `(` and `)`
1477 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1478 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1479 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1480 if fits_single_line {
1481 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1482 } else {
1483 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1484 }
1485 }
1486
rewrite_paren_in_multi_line( context: &RewriteContext<'_>, subexpr: &ast::Expr, shape: Shape, pre_span: Span, post_span: Span, ) -> Option<String>1487 fn rewrite_paren_in_multi_line(
1488 context: &RewriteContext<'_>,
1489 subexpr: &ast::Expr,
1490 shape: Shape,
1491 pre_span: Span,
1492 post_span: Span,
1493 ) -> Option<String> {
1494 let nested_indent = shape.indent.block_indent(context.config);
1495 let nested_shape = Shape::indented(nested_indent, context.config);
1496 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1497 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1498 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1499
1500 let mut result = String::with_capacity(subexpr_str.len() * 2);
1501 result.push('(');
1502 if !pre_comment.is_empty() {
1503 result.push_str(&nested_indent.to_string_with_newline(context.config));
1504 result.push_str(&pre_comment);
1505 }
1506 result.push_str(&nested_indent.to_string_with_newline(context.config));
1507 result.push_str(&subexpr_str);
1508 if !post_comment.is_empty() {
1509 result.push_str(&nested_indent.to_string_with_newline(context.config));
1510 result.push_str(&post_comment);
1511 }
1512 result.push_str(&shape.indent.to_string_with_newline(context.config));
1513 result.push(')');
1514
1515 Some(result)
1516 }
1517
rewrite_index( expr: &ast::Expr, index: &ast::Expr, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>1518 fn rewrite_index(
1519 expr: &ast::Expr,
1520 index: &ast::Expr,
1521 context: &RewriteContext<'_>,
1522 shape: Shape,
1523 ) -> Option<String> {
1524 let expr_str = expr.rewrite(context, shape)?;
1525
1526 let offset = last_line_width(&expr_str) + 1;
1527 let rhs_overhead = shape.rhs_overhead(context.config);
1528 let index_shape = if expr_str.contains('\n') {
1529 Shape::legacy(context.config.max_width(), shape.indent)
1530 .offset_left(offset)
1531 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1532 } else {
1533 match context.config.indent_style() {
1534 IndentStyle::Block => shape
1535 .offset_left(offset)
1536 .and_then(|shape| shape.sub_width(1)),
1537 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1538 }
1539 };
1540 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1541
1542 // Return if index fits in a single line.
1543 match orig_index_rw {
1544 Some(ref index_str) if !index_str.contains('\n') => {
1545 return Some(format!("{}[{}]", expr_str, index_str));
1546 }
1547 _ => (),
1548 }
1549
1550 // Try putting index on the next line and see if it fits in a single line.
1551 let indent = shape.indent.block_indent(context.config);
1552 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1553 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1554 let new_index_rw = index.rewrite(context, index_shape);
1555 match (orig_index_rw, new_index_rw) {
1556 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1557 "{}{}[{}]",
1558 expr_str,
1559 indent.to_string_with_newline(context.config),
1560 new_index_str,
1561 )),
1562 (None, Some(ref new_index_str)) => Some(format!(
1563 "{}{}[{}]",
1564 expr_str,
1565 indent.to_string_with_newline(context.config),
1566 new_index_str,
1567 )),
1568 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1569 _ => None,
1570 }
1571 }
1572
struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool1573 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1574 !has_base && fields.iter().all(|field| !field.is_shorthand)
1575 }
1576
rewrite_struct_lit<'a>( context: &RewriteContext<'_>, path: &ast::Path, qself: &Option<ptr::P<ast::QSelf>>, fields: &'a [ast::ExprField], struct_rest: &ast::StructRest, attrs: &[ast::Attribute], span: Span, shape: Shape, ) -> Option<String>1577 fn rewrite_struct_lit<'a>(
1578 context: &RewriteContext<'_>,
1579 path: &ast::Path,
1580 qself: &Option<ptr::P<ast::QSelf>>,
1581 fields: &'a [ast::ExprField],
1582 struct_rest: &ast::StructRest,
1583 attrs: &[ast::Attribute],
1584 span: Span,
1585 shape: Shape,
1586 ) -> Option<String> {
1587 debug!("rewrite_struct_lit: shape {:?}", shape);
1588
1589 enum StructLitField<'a> {
1590 Regular(&'a ast::ExprField),
1591 Base(&'a ast::Expr),
1592 Rest(Span),
1593 }
1594
1595 // 2 = " {".len()
1596 let path_shape = shape.sub_width(2)?;
1597 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1598
1599 let has_base_or_rest = match struct_rest {
1600 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1601 ast::StructRest::Rest(_) if fields.is_empty() => {
1602 return Some(format!("{} {{ .. }}", path_str));
1603 }
1604 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1605 _ => false,
1606 };
1607
1608 // Foo { a: Foo } - indent is +3, width is -5.
1609 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1610
1611 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1612 let body_lo = context.snippet_provider.span_after(span, "{");
1613 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1614 && context.config.struct_field_align_threshold() > 0
1615 {
1616 rewrite_with_alignment(
1617 fields,
1618 context,
1619 v_shape,
1620 mk_sp(body_lo, span.hi()),
1621 one_line_width,
1622 )?
1623 } else {
1624 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1625 match struct_rest {
1626 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1627 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1628 ast::StructRest::None => None,
1629 }
1630 .into_iter(),
1631 );
1632
1633 let span_lo = |item: &StructLitField<'_>| match *item {
1634 StructLitField::Regular(field) => field.span().lo(),
1635 StructLitField::Base(expr) => {
1636 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1637 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1638 let pos = snippet.find_uncommented("..").unwrap();
1639 last_field_hi + BytePos(pos as u32)
1640 }
1641 StructLitField::Rest(span) => span.lo(),
1642 };
1643 let span_hi = |item: &StructLitField<'_>| match *item {
1644 StructLitField::Regular(field) => field.span().hi(),
1645 StructLitField::Base(expr) => expr.span.hi(),
1646 StructLitField::Rest(span) => span.hi(),
1647 };
1648 let rewrite = |item: &StructLitField<'_>| match *item {
1649 StructLitField::Regular(field) => {
1650 // The 1 taken from the v_budget is for the comma.
1651 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1652 }
1653 StructLitField::Base(expr) => {
1654 // 2 = ..
1655 expr.rewrite(context, v_shape.offset_left(2)?)
1656 .map(|s| format!("..{}", s))
1657 }
1658 StructLitField::Rest(_) => Some("..".to_owned()),
1659 };
1660
1661 let items = itemize_list(
1662 context.snippet_provider,
1663 field_iter,
1664 "}",
1665 ",",
1666 span_lo,
1667 span_hi,
1668 rewrite,
1669 body_lo,
1670 span.hi(),
1671 false,
1672 );
1673 let item_vec = items.collect::<Vec<_>>();
1674
1675 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1676 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1677
1678 let ends_with_comma = span_ends_with_comma(context, span);
1679 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1680
1681 let fmt = struct_lit_formatting(
1682 nested_shape,
1683 tactic,
1684 context,
1685 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1686 );
1687
1688 write_list(&item_vec, &fmt)?
1689 };
1690
1691 let fields_str =
1692 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1693 Some(format!("{} {{{}}}", path_str, fields_str))
1694
1695 // FIXME if context.config.indent_style() == Visual, but we run out
1696 // of space, we should fall back to BlockIndent.
1697 }
1698
wrap_struct_field( context: &RewriteContext<'_>, attrs: &[ast::Attribute], fields_str: &str, shape: Shape, nested_shape: Shape, one_line_width: usize, ) -> Option<String>1699 pub(crate) fn wrap_struct_field(
1700 context: &RewriteContext<'_>,
1701 attrs: &[ast::Attribute],
1702 fields_str: &str,
1703 shape: Shape,
1704 nested_shape: Shape,
1705 one_line_width: usize,
1706 ) -> Option<String> {
1707 let should_vertical = context.config.indent_style() == IndentStyle::Block
1708 && (fields_str.contains('\n')
1709 || !context.config.struct_lit_single_line()
1710 || fields_str.len() > one_line_width);
1711
1712 let inner_attrs = &inner_attributes(attrs);
1713 if inner_attrs.is_empty() {
1714 if should_vertical {
1715 Some(format!(
1716 "{}{}{}",
1717 nested_shape.indent.to_string_with_newline(context.config),
1718 fields_str,
1719 shape.indent.to_string_with_newline(context.config)
1720 ))
1721 } else {
1722 // One liner or visual indent.
1723 Some(format!(" {} ", fields_str))
1724 }
1725 } else {
1726 Some(format!(
1727 "{}{}{}{}{}",
1728 nested_shape.indent.to_string_with_newline(context.config),
1729 inner_attrs.rewrite(context, shape)?,
1730 nested_shape.indent.to_string_with_newline(context.config),
1731 fields_str,
1732 shape.indent.to_string_with_newline(context.config)
1733 ))
1734 }
1735 }
1736
struct_lit_field_separator(config: &Config) -> &str1737 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1738 colon_spaces(config)
1739 }
1740
rewrite_field( context: &RewriteContext<'_>, field: &ast::ExprField, shape: Shape, prefix_max_width: usize, ) -> Option<String>1741 pub(crate) fn rewrite_field(
1742 context: &RewriteContext<'_>,
1743 field: &ast::ExprField,
1744 shape: Shape,
1745 prefix_max_width: usize,
1746 ) -> Option<String> {
1747 if contains_skip(&field.attrs) {
1748 return Some(context.snippet(field.span()).to_owned());
1749 }
1750 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1751 if !attrs_str.is_empty() {
1752 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1753 };
1754 let name = context.snippet(field.ident.span);
1755 if field.is_shorthand {
1756 Some(attrs_str + name)
1757 } else {
1758 let mut separator = String::from(struct_lit_field_separator(context.config));
1759 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1760 separator.push(' ');
1761 }
1762 let overhead = name.len() + separator.len();
1763 let expr_shape = shape.offset_left(overhead)?;
1764 let expr = field.expr.rewrite(context, expr_shape);
1765 let is_lit = matches!(field.expr.kind, ast::ExprKind::Lit(_));
1766 match expr {
1767 Some(ref e)
1768 if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() =>
1769 {
1770 Some(attrs_str + name)
1771 }
1772 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1773 None => {
1774 let expr_offset = shape.indent.block_indent(context.config);
1775 let expr = field
1776 .expr
1777 .rewrite(context, Shape::indented(expr_offset, context.config));
1778 expr.map(|s| {
1779 format!(
1780 "{}{}:\n{}{}",
1781 attrs_str,
1782 name,
1783 expr_offset.to_string(context.config),
1784 s
1785 )
1786 })
1787 }
1788 }
1789 }
1790 }
1791
rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( context: &RewriteContext<'_>, mut items: impl Iterator<Item = &'a T>, span: Span, shape: Shape, is_singleton_tuple: bool, ) -> Option<String>1792 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1793 context: &RewriteContext<'_>,
1794 mut items: impl Iterator<Item = &'a T>,
1795 span: Span,
1796 shape: Shape,
1797 is_singleton_tuple: bool,
1798 ) -> Option<String> {
1799 // In case of length 1, need a trailing comma
1800 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1801 if is_singleton_tuple {
1802 // 3 = "(" + ",)"
1803 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1804 return items
1805 .next()
1806 .unwrap()
1807 .rewrite(context, nested_shape)
1808 .map(|s| format!("({},)", s));
1809 }
1810
1811 let list_lo = context.snippet_provider.span_after(span, "(");
1812 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1813 let items = itemize_list(
1814 context.snippet_provider,
1815 items,
1816 ")",
1817 ",",
1818 |item| item.span().lo(),
1819 |item| item.span().hi(),
1820 |item| item.rewrite(context, nested_shape),
1821 list_lo,
1822 span.hi() - BytePos(1),
1823 false,
1824 );
1825 let item_vec: Vec<_> = items.collect();
1826 let tactic = definitive_tactic(
1827 &item_vec,
1828 ListTactic::HorizontalVertical,
1829 Separator::Comma,
1830 nested_shape.width,
1831 );
1832 let fmt = ListFormatting::new(nested_shape, context.config)
1833 .tactic(tactic)
1834 .ends_with_newline(false);
1835 let list_str = write_list(&item_vec, &fmt)?;
1836
1837 Some(format!("({})", list_str))
1838 }
1839
rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>( context: &'a RewriteContext<'_>, items: impl Iterator<Item = &'a T>, span: Span, shape: Shape, is_singleton_tuple: bool, ) -> Option<String>1840 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1841 context: &'a RewriteContext<'_>,
1842 items: impl Iterator<Item = &'a T>,
1843 span: Span,
1844 shape: Shape,
1845 is_singleton_tuple: bool,
1846 ) -> Option<String> {
1847 debug!("rewrite_tuple {:?}", shape);
1848 if context.use_block_indent() {
1849 // We use the same rule as function calls for rewriting tuples.
1850 let force_tactic = if context.inside_macro() {
1851 if span_ends_with_comma(context, span) {
1852 Some(SeparatorTactic::Always)
1853 } else {
1854 Some(SeparatorTactic::Never)
1855 }
1856 } else if is_singleton_tuple {
1857 Some(SeparatorTactic::Always)
1858 } else {
1859 None
1860 };
1861 overflow::rewrite_with_parens(
1862 context,
1863 "",
1864 items,
1865 shape,
1866 span,
1867 context.config.fn_call_width(),
1868 force_tactic,
1869 )
1870 } else {
1871 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1872 }
1873 }
1874
rewrite_unary_prefix<R: Rewrite>( context: &RewriteContext<'_>, prefix: &str, rewrite: &R, shape: Shape, ) -> Option<String>1875 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1876 context: &RewriteContext<'_>,
1877 prefix: &str,
1878 rewrite: &R,
1879 shape: Shape,
1880 ) -> Option<String> {
1881 rewrite
1882 .rewrite(context, shape.offset_left(prefix.len())?)
1883 .map(|r| format!("{}{}", prefix, r))
1884 }
1885
1886 // FIXME: this is probably not correct for multi-line Rewrites. we should
1887 // subtract suffix.len() from the last line budget, not the first!
rewrite_unary_suffix<R: Rewrite>( context: &RewriteContext<'_>, suffix: &str, rewrite: &R, shape: Shape, ) -> Option<String>1888 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1889 context: &RewriteContext<'_>,
1890 suffix: &str,
1891 rewrite: &R,
1892 shape: Shape,
1893 ) -> Option<String> {
1894 rewrite
1895 .rewrite(context, shape.sub_width(suffix.len())?)
1896 .map(|mut r| {
1897 r.push_str(suffix);
1898 r
1899 })
1900 }
1901
rewrite_unary_op( context: &RewriteContext<'_>, op: ast::UnOp, expr: &ast::Expr, shape: Shape, ) -> Option<String>1902 fn rewrite_unary_op(
1903 context: &RewriteContext<'_>,
1904 op: ast::UnOp,
1905 expr: &ast::Expr,
1906 shape: Shape,
1907 ) -> Option<String> {
1908 // For some reason, an UnOp is not spanned like BinOp!
1909 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1910 }
1911
1912 pub(crate) enum RhsAssignKind<'ast> {
1913 Expr(&'ast ast::ExprKind, Span),
1914 Bounds,
1915 Ty,
1916 }
1917
1918 impl<'ast> RhsAssignKind<'ast> {
1919 // TODO(calebcartwright)
1920 // Preemptive addition for handling RHS with chains, not yet utilized.
1921 // It may make more sense to construct the chain first and then check
1922 // whether there are actually chain elements.
1923 #[allow(dead_code)]
is_chain(&self) -> bool1924 fn is_chain(&self) -> bool {
1925 match self {
1926 RhsAssignKind::Expr(kind, _) => {
1927 matches!(
1928 kind,
1929 ast::ExprKind::Try(..)
1930 | ast::ExprKind::Field(..)
1931 | ast::ExprKind::MethodCall(..)
1932 | ast::ExprKind::Await(_, _)
1933 )
1934 }
1935 _ => false,
1936 }
1937 }
1938 }
1939
rewrite_assignment( context: &RewriteContext<'_>, lhs: &ast::Expr, rhs: &ast::Expr, op: Option<&ast::BinOp>, shape: Shape, ) -> Option<String>1940 fn rewrite_assignment(
1941 context: &RewriteContext<'_>,
1942 lhs: &ast::Expr,
1943 rhs: &ast::Expr,
1944 op: Option<&ast::BinOp>,
1945 shape: Shape,
1946 ) -> Option<String> {
1947 let operator_str = match op {
1948 Some(op) => context.snippet(op.span),
1949 None => "=",
1950 };
1951
1952 // 1 = space between lhs and operator.
1953 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1954 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1955
1956 rewrite_assign_rhs(
1957 context,
1958 lhs_str,
1959 rhs,
1960 &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1961 shape,
1962 )
1963 }
1964
1965 /// Controls where to put the rhs.
1966 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1967 pub(crate) enum RhsTactics {
1968 /// Use heuristics.
1969 Default,
1970 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1971 ForceNextLineWithoutIndent,
1972 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1973 /// did not work.
1974 AllowOverflow,
1975 }
1976
1977 // The left hand side must contain everything up to, and including, the
1978 // assignment operator.
rewrite_assign_rhs<S: Into<String>, R: Rewrite>( context: &RewriteContext<'_>, lhs: S, ex: &R, rhs_kind: &RhsAssignKind<'_>, shape: Shape, ) -> Option<String>1979 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1980 context: &RewriteContext<'_>,
1981 lhs: S,
1982 ex: &R,
1983 rhs_kind: &RhsAssignKind<'_>,
1984 shape: Shape,
1985 ) -> Option<String> {
1986 rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1987 }
1988
rewrite_assign_rhs_expr<R: Rewrite>( context: &RewriteContext<'_>, lhs: &str, ex: &R, shape: Shape, rhs_kind: &RhsAssignKind<'_>, rhs_tactics: RhsTactics, ) -> Option<String>1989 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1990 context: &RewriteContext<'_>,
1991 lhs: &str,
1992 ex: &R,
1993 shape: Shape,
1994 rhs_kind: &RhsAssignKind<'_>,
1995 rhs_tactics: RhsTactics,
1996 ) -> Option<String> {
1997 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1998 shape.indent.width()
1999 } else {
2000 0
2001 });
2002 // 1 = space between operator and rhs.
2003 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
2004 width: 0,
2005 offset: shape.offset + last_line_width + 1,
2006 ..shape
2007 });
2008 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
2009 lhs.trim_end().len() > offset + 1
2010 } else {
2011 false
2012 };
2013
2014 choose_rhs(
2015 context,
2016 ex,
2017 orig_shape,
2018 ex.rewrite(context, orig_shape),
2019 rhs_kind,
2020 rhs_tactics,
2021 has_rhs_comment,
2022 )
2023 }
2024
rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>( context: &RewriteContext<'_>, lhs: S, ex: &R, shape: Shape, rhs_kind: &RhsAssignKind<'_>, rhs_tactics: RhsTactics, ) -> Option<String>2025 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2026 context: &RewriteContext<'_>,
2027 lhs: S,
2028 ex: &R,
2029 shape: Shape,
2030 rhs_kind: &RhsAssignKind<'_>,
2031 rhs_tactics: RhsTactics,
2032 ) -> Option<String> {
2033 let lhs = lhs.into();
2034 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2035 Some(lhs + &rhs)
2036 }
2037
rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>( context: &RewriteContext<'_>, lhs: S, ex: &R, shape: Shape, rhs_kind: &RhsAssignKind<'_>, rhs_tactics: RhsTactics, between_span: Span, allow_extend: bool, ) -> Option<String>2038 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
2039 context: &RewriteContext<'_>,
2040 lhs: S,
2041 ex: &R,
2042 shape: Shape,
2043 rhs_kind: &RhsAssignKind<'_>,
2044 rhs_tactics: RhsTactics,
2045 between_span: Span,
2046 allow_extend: bool,
2047 ) -> Option<String> {
2048 let lhs = lhs.into();
2049 let contains_comment = contains_comment(context.snippet(between_span));
2050 let shape = if contains_comment {
2051 shape.block_left(context.config.tab_spaces())?
2052 } else {
2053 shape
2054 };
2055 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2056
2057 if contains_comment {
2058 let rhs = rhs.trim_start();
2059 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2060 } else {
2061 Some(lhs + &rhs)
2062 }
2063 }
2064
choose_rhs<R: Rewrite>( context: &RewriteContext<'_>, expr: &R, shape: Shape, orig_rhs: Option<String>, _rhs_kind: &RhsAssignKind<'_>, rhs_tactics: RhsTactics, has_rhs_comment: bool, ) -> Option<String>2065 fn choose_rhs<R: Rewrite>(
2066 context: &RewriteContext<'_>,
2067 expr: &R,
2068 shape: Shape,
2069 orig_rhs: Option<String>,
2070 _rhs_kind: &RhsAssignKind<'_>,
2071 rhs_tactics: RhsTactics,
2072 has_rhs_comment: bool,
2073 ) -> Option<String> {
2074 match orig_rhs {
2075 Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2076 Some(ref new_str)
2077 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2078 {
2079 Some(format!(" {}", new_str))
2080 }
2081 _ => {
2082 // Expression did not fit on the same line as the identifier.
2083 // Try splitting the line and see if that works better.
2084 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2085 let new_rhs = expr.rewrite(context, new_shape);
2086 let new_indent_str = &shape
2087 .indent
2088 .block_indent(context.config)
2089 .to_string_with_newline(context.config);
2090 let before_space_str = if has_rhs_comment { "" } else { " " };
2091
2092 match (orig_rhs, new_rhs) {
2093 (Some(ref orig_rhs), Some(ref new_rhs))
2094 if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) =>
2095 {
2096 Some(format!("{}{}", before_space_str, orig_rhs))
2097 }
2098 (Some(ref orig_rhs), Some(ref new_rhs))
2099 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2100 {
2101 Some(format!("{}{}", new_indent_str, new_rhs))
2102 }
2103 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2104 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2105 let shape = shape.infinite_width();
2106 expr.rewrite(context, shape)
2107 .map(|s| format!("{}{}", before_space_str, s))
2108 }
2109 (None, None) => None,
2110 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2111 }
2112 }
2113 }
2114 }
2115
shape_from_rhs_tactic( context: &RewriteContext<'_>, shape: Shape, rhs_tactic: RhsTactics, ) -> Option<Shape>2116 fn shape_from_rhs_tactic(
2117 context: &RewriteContext<'_>,
2118 shape: Shape,
2119 rhs_tactic: RhsTactics,
2120 ) -> Option<Shape> {
2121 match rhs_tactic {
2122 RhsTactics::ForceNextLineWithoutIndent => shape
2123 .with_max_width(context.config)
2124 .sub_width(shape.indent.width()),
2125 RhsTactics::Default | RhsTactics::AllowOverflow => {
2126 Shape::indented(shape.indent.block_indent(context.config), context.config)
2127 .sub_width(shape.rhs_overhead(context.config))
2128 }
2129 }
2130 }
2131
2132 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2133 /// original's line formatting.
2134 ///
2135 /// It is considered better if:
2136 /// 1. the tactic is ForceNextLineWithoutIndent
2137 /// 2. next_line_rhs doesn't have newlines
2138 /// 3. the original line has more newlines than next_line_rhs
2139 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2140 /// doesn't
prefer_next_line( orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics, ) -> bool2141 pub(crate) fn prefer_next_line(
2142 orig_rhs: &str,
2143 next_line_rhs: &str,
2144 rhs_tactics: RhsTactics,
2145 ) -> bool {
2146 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2147 || !next_line_rhs.contains('\n')
2148 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2149 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2150 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2151 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2152 }
2153
rewrite_expr_addrof( context: &RewriteContext<'_>, borrow_kind: ast::BorrowKind, mutability: ast::Mutability, expr: &ast::Expr, shape: Shape, ) -> Option<String>2154 fn rewrite_expr_addrof(
2155 context: &RewriteContext<'_>,
2156 borrow_kind: ast::BorrowKind,
2157 mutability: ast::Mutability,
2158 expr: &ast::Expr,
2159 shape: Shape,
2160 ) -> Option<String> {
2161 let operator_str = match (mutability, borrow_kind) {
2162 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2163 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2164 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2165 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2166 };
2167 rewrite_unary_prefix(context, operator_str, expr, shape)
2168 }
2169
is_method_call(expr: &ast::Expr) -> bool2170 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2171 match expr.kind {
2172 ast::ExprKind::MethodCall(..) => true,
2173 ast::ExprKind::AddrOf(_, _, ref expr)
2174 | ast::ExprKind::Cast(ref expr, _)
2175 | ast::ExprKind::Try(ref expr)
2176 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2177 _ => false,
2178 }
2179 }
2180
2181 #[cfg(test)]
2182 mod test {
2183 use super::last_line_offsetted;
2184
2185 #[test]
test_last_line_offsetted()2186 fn test_last_line_offsetted() {
2187 let lines = "one\n two";
2188 assert_eq!(last_line_offsetted(2, lines), true);
2189 assert_eq!(last_line_offsetted(4, lines), false);
2190 assert_eq!(last_line_offsetted(6, lines), false);
2191
2192 let lines = "one two";
2193 assert_eq!(last_line_offsetted(2, lines), false);
2194 assert_eq!(last_line_offsetted(0, lines), false);
2195
2196 let lines = "\ntwo";
2197 assert_eq!(last_line_offsetted(2, lines), false);
2198 assert_eq!(last_line_offsetted(0, lines), false);
2199
2200 let lines = "one\n two three";
2201 assert_eq!(last_line_offsetted(2, lines), true);
2202 let lines = "one\n two three";
2203 assert_eq!(last_line_offsetted(2, lines), false);
2204 }
2205 }
2206