1use rustc_ast::{Label, ast};
2use rustc_span::Span;
3use thin_vec::thin_vec;
4use tracing::debug;
5
6use crate::attr::get_attrs_from_stmt;
7use crate::config::StyleEdition;
8use crate::config::lists::*;
9use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
10use crate::items::{span_hi_for_param, span_lo_for_param};
11use crate::lists::{ListFormatting, Separator, definitive_tactic, itemize_list, write_list};
12use crate::overflow::OverflowableItem;
13use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
14use crate::shape::Shape;
15use crate::source_map::SpanUtils;
16use crate::types::rewrite_bound_params;
17use crate::utils::{NodeIdExt, last_line_width, left_most_sub_expr, stmt_expr};
18
19pub(crate) fn rewrite_closure(
30 binder: &ast::ClosureBinder,
31 constness: ast::Const,
32 capture: ast::CaptureBy,
33 coroutine_kind: &Option<ast::CoroutineKind>,
34 movability: ast::Movability,
35 fn_decl: &ast::FnDecl,
36 body: &ast::Expr,
37 span: Span,
38 context: &RewriteContext<'_>,
39 shape: Shape,
40) -> RewriteResult {
41 debug!("rewrite_closure {:?}", body);
42
43 let (prefix, extra_offset) = rewrite_closure_fn_decl(
44 binder,
45 constness,
46 capture,
47 coroutine_kind,
48 movability,
49 fn_decl,
50 body,
51 span,
52 context,
53 shape,
54 )?;
55 let body_shape = shape.offset_left(extra_offset, span)?;
57
58 if let ast::ExprKind::Block(ref block, _) = body.kind {
59 if block.stmts.is_empty() && !block_contains_comment(context, block) {
61 return body
62 .rewrite_result(context, shape)
63 .map(|s| format!("{} {}", prefix, s));
64 }
65
66 let result = match fn_decl.output {
67 ast::FnRetTy::Default(_) if !context.inside_macro() => {
68 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
69 }
70 _ => Err(RewriteError::Unknown),
71 };
72
73 result.or_else(|_| {
74 rewrite_closure_block(body, &prefix, context, body_shape)
76 })
77 } else {
78 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|_| {
79 rewrite_closure_with_block(body, &prefix, context, body_shape)
82 })
83 }
84}
85
86fn try_rewrite_without_block(
87 expr: &ast::Expr,
88 prefix: &str,
89 context: &RewriteContext<'_>,
90 shape: Shape,
91 body_shape: Shape,
92) -> RewriteResult {
93 let expr = get_inner_expr(expr, prefix, context);
94
95 if is_block_closure_forced(context, expr) {
96 rewrite_closure_with_block(expr, prefix, context, shape)
97 } else {
98 rewrite_closure_expr(expr, prefix, context, body_shape)
99 }
100}
101
102fn get_inner_expr<'a>(
103 expr: &'a ast::Expr,
104 prefix: &str,
105 context: &RewriteContext<'_>,
106) -> &'a ast::Expr {
107 if let ast::ExprKind::Block(ref block, ref label) = expr.kind {
108 if !needs_block(block, label, prefix, context) {
109 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
112 return get_inner_expr(expr, prefix, context);
113 }
114 }
115 }
116
117 expr
118}
119
120fn needs_block(
122 block: &ast::Block,
123 label: &Option<Label>,
124 prefix: &str,
125 context: &RewriteContext<'_>,
126) -> bool {
127 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
128 !get_attrs_from_stmt(first_stmt).is_empty()
129 });
130
131 is_unsafe_block(block)
132 || block.stmts.len() > 1
133 || has_attributes
134 || block_contains_comment(context, block)
135 || prefix.contains('\n')
136 || label.is_some()
137}
138
139fn veto_block(e: &ast::Expr) -> bool {
140 match e.kind {
141 ast::ExprKind::Call(..)
142 | ast::ExprKind::Binary(..)
143 | ast::ExprKind::Cast(..)
144 | ast::ExprKind::Type(..)
145 | ast::ExprKind::Assign(..)
146 | ast::ExprKind::AssignOp(..)
147 | ast::ExprKind::Field(..)
148 | ast::ExprKind::Index(..)
149 | ast::ExprKind::Range(..)
150 | ast::ExprKind::Try(..) => true,
151 _ => false,
152 }
153}
154
155fn rewrite_closure_with_block(
158 body: &ast::Expr,
159 prefix: &str,
160 context: &RewriteContext<'_>,
161 shape: Shape,
162) -> RewriteResult {
163 let left_most = left_most_sub_expr(body);
164 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
165 if veto_block {
166 return Err(RewriteError::Unknown);
167 }
168
169 let block = ast::Block {
170 stmts: thin_vec![ast::Stmt {
171 id: ast::NodeId::root(),
172 kind: ast::StmtKind::Expr(Box::new(body.clone())),
173 span: body.span,
174 }],
175 id: ast::NodeId::root(),
176 rules: ast::BlockCheckMode::Default,
177 span: body
178 .attrs
179 .first()
180 .map(|attr| attr.span.to(body.span))
181 .unwrap_or(body.span),
182 };
183 let block = crate::expr::rewrite_block_with_visitor(
184 context,
185 "",
186 &block,
187 Some(&body.attrs),
188 None,
189 shape,
190 false,
191 )?;
192 Ok(format!("{prefix} {block}"))
193}
194
195fn rewrite_closure_expr(
197 expr: &ast::Expr,
198 prefix: &str,
199 context: &RewriteContext<'_>,
200 shape: Shape,
201) -> RewriteResult {
202 fn allow_multi_line(expr: &ast::Expr) -> bool {
203 match expr.kind {
204 ast::ExprKind::Match(..)
205 | ast::ExprKind::Gen(..)
206 | ast::ExprKind::Block(..)
207 | ast::ExprKind::TryBlock(..)
208 | ast::ExprKind::Loop(..)
209 | ast::ExprKind::Struct(..) => true,
210
211 ast::ExprKind::AddrOf(_, _, ref expr)
212 | ast::ExprKind::Try(ref expr)
213 | ast::ExprKind::Unary(_, ref expr)
214 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
215
216 _ => false,
217 }
218 }
219
220 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
223 || context.config.force_multiline_blocks();
224 expr.rewrite_result(context, shape)
225 .and_then(|rw| {
226 if veto_multiline && rw.contains('\n') {
227 Err(RewriteError::Unknown)
228 } else {
229 Ok(rw)
230 }
231 })
232 .map(|rw| format!("{} {}", prefix, rw))
233}
234
235fn rewrite_closure_block(
237 block: &ast::Expr,
238 prefix: &str,
239 context: &RewriteContext<'_>,
240 shape: Shape,
241) -> RewriteResult {
242 debug_assert!(
243 matches!(block.kind, ast::ExprKind::Block(..)),
244 "expected a block expression"
245 );
246
247 Ok(format!(
248 "{} {}",
249 prefix,
250 block.rewrite_result(context, shape)?
251 ))
252}
253
254fn rewrite_closure_fn_decl(
256 binder: &ast::ClosureBinder,
257 constness: ast::Const,
258 capture: ast::CaptureBy,
259 coroutine_kind: &Option<ast::CoroutineKind>,
260 movability: ast::Movability,
261 fn_decl: &ast::FnDecl,
262 body: &ast::Expr,
263 span: Span,
264 context: &RewriteContext<'_>,
265 shape: Shape,
266) -> Result<(String, usize), RewriteError> {
267 let binder = match binder {
268 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
269 "for<> ".to_owned()
270 }
271 ast::ClosureBinder::For { generic_params, .. } => {
272 let lifetime_str =
273 rewrite_bound_params(context, shape, generic_params).unknown_error()?;
274 format!("for<{lifetime_str}> ")
275 }
276 ast::ClosureBinder::NotPresent => "".to_owned(),
277 };
278
279 let const_ = if matches!(constness, ast::Const::Yes(_)) {
280 "const "
281 } else {
282 ""
283 };
284
285 let immovable = if movability == ast::Movability::Static {
286 "static "
287 } else {
288 ""
289 };
290 let coro = match coroutine_kind {
291 Some(ast::CoroutineKind::Async { .. }) => "async ",
292 Some(ast::CoroutineKind::Gen { .. }) => "gen ",
293 Some(ast::CoroutineKind::AsyncGen { .. }) => "async gen ",
294 None => "",
295 };
296 let capture_str = match capture {
297 ast::CaptureBy::Value { .. } => "move ",
298 ast::CaptureBy::Use { .. } => "use ",
299 ast::CaptureBy::Ref => "",
300 };
301 let offset = binder.len() + const_.len() + immovable.len() + coro.len() + capture_str.len();
304 let nested_shape = shape.shrink_left(offset, span)?.sub_width(4, span)?;
305
306 let param_offset = nested_shape.indent + 1;
308 let param_shape = nested_shape.offset_left(1, span)?.visual_indent(0);
309 let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
310
311 let param_items = itemize_list(
312 context.snippet_provider,
313 fn_decl.inputs.iter(),
314 "|",
315 ",",
316 |param| span_lo_for_param(param),
317 |param| span_hi_for_param(context, param),
318 |param| param.rewrite_result(context, param_shape),
319 context.snippet_provider.span_after(span, "|"),
320 body.span.lo(),
321 false,
322 );
323 let item_vec = param_items.collect::<Vec<_>>();
324 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
326 let tactic = definitive_tactic(
327 &item_vec,
328 ListTactic::HorizontalVertical,
329 Separator::Comma,
330 horizontal_budget,
331 );
332 let param_shape = match tactic {
333 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1, span)?,
334 _ => param_shape,
335 };
336
337 let fmt = ListFormatting::new(param_shape, context.config)
338 .tactic(tactic)
339 .preserve_newline(true);
340 let list_str = write_list(&item_vec, &fmt)?;
341 let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|");
342
343 if !ret_str.is_empty() {
344 if prefix.contains('\n') {
345 prefix.push('\n');
346 prefix.push_str(¶m_offset.to_string(context.config));
347 } else {
348 prefix.push(' ');
349 }
350 prefix.push_str(&ret_str);
351 }
352 let extra_offset = last_line_width(&prefix) + 1;
354
355 Ok((prefix, extra_offset))
356}
357
358pub(crate) fn rewrite_last_closure(
361 context: &RewriteContext<'_>,
362 expr: &ast::Expr,
363 shape: Shape,
364) -> RewriteResult {
365 debug!("rewrite_last_closure {:?}", expr);
366
367 if let ast::ExprKind::Closure(ref closure) = expr.kind {
368 let ast::Closure {
369 ref binder,
370 constness,
371 capture_clause,
372 ref coroutine_kind,
373 movability,
374 ref fn_decl,
375 ref body,
376 fn_decl_span: _,
377 fn_arg_span: _,
378 } = **closure;
379 let body = match body.kind {
380 ast::ExprKind::Block(ref block, ref label)
381 if !is_unsafe_block(block)
382 && !context.inside_macro()
383 && is_simple_block(context, block, Some(&body.attrs))
384 && label.is_none() =>
385 {
386 stmt_expr(&block.stmts[0]).unwrap_or(body)
387 }
388 _ => body,
389 };
390 let (prefix, extra_offset) = rewrite_closure_fn_decl(
391 binder,
392 constness,
393 capture_clause,
394 coroutine_kind,
395 movability,
396 fn_decl,
397 body,
398 expr.span,
399 context,
400 shape,
401 )?;
402 if prefix.contains('\n') {
404 return Err(RewriteError::Unknown);
405 }
406
407 let body_shape = shape.offset_left(extra_offset, expr.span)?;
408
409 if is_block_closure_forced(context, body) {
411 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
412 |body_str| {
413 match fn_decl.output {
414 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
415 match rewrite_closure_expr(body, &prefix, context, shape) {
419 Ok(single_line_body_str)
420 if !single_line_body_str.contains('\n') =>
421 {
422 single_line_body_str
423 }
424 _ => body_str,
425 }
426 }
427 _ => body_str,
428 }
429 },
430 );
431 }
432
433 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
436 cond.contains('\n') || cond.len() > body_shape.width
437 });
438 if is_multi_lined_cond {
439 return rewrite_closure_with_block(body, &prefix, context, body_shape);
440 }
441
442 return expr.rewrite_result(context, shape);
444 }
445 Err(RewriteError::Unknown)
446}
447
448pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
450 args.iter()
451 .filter_map(OverflowableItem::to_expr)
452 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
453 .count()
454 > 1
455}
456
457fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
458 if context.inside_macro() {
460 false
461 } else {
462 is_block_closure_forced_inner(expr, context.config.style_edition())
463 }
464}
465
466fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
467 match expr.kind {
468 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
469 ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
470 ast::ExprKind::AddrOf(_, _, ref expr)
471 | ast::ExprKind::Try(ref expr)
472 | ast::ExprKind::Unary(_, ref expr)
473 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
474 _ => false,
475 }
476}
477
478fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
487 match e.kind {
488 ast::ExprKind::If(..)
489 | ast::ExprKind::Match(..)
490 | ast::ExprKind::Block(..)
491 | ast::ExprKind::While(..)
492 | ast::ExprKind::Loop(..)
493 | ast::ExprKind::ForLoop { .. }
494 | ast::ExprKind::TryBlock(..) => false,
495 _ => true,
496 }
497}