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 tokens: None,
178 span: body
179 .attrs
180 .first()
181 .map(|attr| attr.span.to(body.span))
182 .unwrap_or(body.span),
183 };
184 let block = crate::expr::rewrite_block_with_visitor(
185 context,
186 "",
187 &block,
188 Some(&body.attrs),
189 None,
190 shape,
191 false,
192 )?;
193 Ok(format!("{prefix} {block}"))
194}
195
196fn rewrite_closure_expr(
198 expr: &ast::Expr,
199 prefix: &str,
200 context: &RewriteContext<'_>,
201 shape: Shape,
202) -> RewriteResult {
203 fn allow_multi_line(expr: &ast::Expr) -> bool {
204 match expr.kind {
205 ast::ExprKind::Match(..)
206 | ast::ExprKind::Gen(..)
207 | ast::ExprKind::Block(..)
208 | ast::ExprKind::TryBlock(..)
209 | ast::ExprKind::Loop(..)
210 | ast::ExprKind::Struct(..) => true,
211
212 ast::ExprKind::AddrOf(_, _, ref expr)
213 | ast::ExprKind::Try(ref expr)
214 | ast::ExprKind::Unary(_, ref expr)
215 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
216
217 _ => false,
218 }
219 }
220
221 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
224 || context.config.force_multiline_blocks();
225 expr.rewrite_result(context, shape)
226 .and_then(|rw| {
227 if veto_multiline && rw.contains('\n') {
228 Err(RewriteError::Unknown)
229 } else {
230 Ok(rw)
231 }
232 })
233 .map(|rw| format!("{} {}", prefix, rw))
234}
235
236fn rewrite_closure_block(
238 block: &ast::Expr,
239 prefix: &str,
240 context: &RewriteContext<'_>,
241 shape: Shape,
242) -> RewriteResult {
243 debug_assert!(
244 matches!(block.kind, ast::ExprKind::Block(..)),
245 "expected a block expression"
246 );
247
248 Ok(format!(
249 "{} {}",
250 prefix,
251 block.rewrite_result(context, shape)?
252 ))
253}
254
255fn rewrite_closure_fn_decl(
257 binder: &ast::ClosureBinder,
258 constness: ast::Const,
259 capture: ast::CaptureBy,
260 coroutine_kind: &Option<ast::CoroutineKind>,
261 movability: ast::Movability,
262 fn_decl: &ast::FnDecl,
263 body: &ast::Expr,
264 span: Span,
265 context: &RewriteContext<'_>,
266 shape: Shape,
267) -> Result<(String, usize), RewriteError> {
268 let binder = match binder {
269 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
270 "for<> ".to_owned()
271 }
272 ast::ClosureBinder::For { generic_params, .. } => {
273 let lifetime_str =
274 rewrite_bound_params(context, shape, generic_params).unknown_error()?;
275 format!("for<{lifetime_str}> ")
276 }
277 ast::ClosureBinder::NotPresent => "".to_owned(),
278 };
279
280 let const_ = if matches!(constness, ast::Const::Yes(_)) {
281 "const "
282 } else {
283 ""
284 };
285
286 let immovable = if movability == ast::Movability::Static {
287 "static "
288 } else {
289 ""
290 };
291 let coro = match coroutine_kind {
292 Some(ast::CoroutineKind::Async { .. }) => "async ",
293 Some(ast::CoroutineKind::Gen { .. }) => "gen ",
294 Some(ast::CoroutineKind::AsyncGen { .. }) => "async gen ",
295 None => "",
296 };
297 let capture_str = match capture {
298 ast::CaptureBy::Value { .. } => "move ",
299 ast::CaptureBy::Use { .. } => "use ",
300 ast::CaptureBy::Ref => "",
301 };
302 let offset = binder.len() + const_.len() + immovable.len() + coro.len() + capture_str.len();
305 let nested_shape = shape.shrink_left(offset, span)?.sub_width(4, span)?;
306
307 let param_offset = nested_shape.indent + 1;
309 let param_shape = nested_shape.offset_left(1, span)?.visual_indent(0);
310 let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
311
312 let param_items = itemize_list(
313 context.snippet_provider,
314 fn_decl.inputs.iter(),
315 "|",
316 ",",
317 |param| span_lo_for_param(param),
318 |param| span_hi_for_param(context, param),
319 |param| param.rewrite_result(context, param_shape),
320 context.snippet_provider.span_after(span, "|"),
321 body.span.lo(),
322 false,
323 );
324 let item_vec = param_items.collect::<Vec<_>>();
325 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
327 let tactic = definitive_tactic(
328 &item_vec,
329 ListTactic::HorizontalVertical,
330 Separator::Comma,
331 horizontal_budget,
332 );
333 let param_shape = match tactic {
334 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1, span)?,
335 _ => param_shape,
336 };
337
338 let fmt = ListFormatting::new(param_shape, context.config)
339 .tactic(tactic)
340 .preserve_newline(true);
341 let list_str = write_list(&item_vec, &fmt)?;
342 let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|");
343
344 if !ret_str.is_empty() {
345 if prefix.contains('\n') {
346 prefix.push('\n');
347 prefix.push_str(¶m_offset.to_string(context.config));
348 } else {
349 prefix.push(' ');
350 }
351 prefix.push_str(&ret_str);
352 }
353 let extra_offset = last_line_width(&prefix) + 1;
355
356 Ok((prefix, extra_offset))
357}
358
359pub(crate) fn rewrite_last_closure(
362 context: &RewriteContext<'_>,
363 expr: &ast::Expr,
364 shape: Shape,
365) -> RewriteResult {
366 debug!("rewrite_last_closure {:?}", expr);
367
368 if let ast::ExprKind::Closure(ref closure) = expr.kind {
369 let ast::Closure {
370 ref binder,
371 constness,
372 capture_clause,
373 ref coroutine_kind,
374 movability,
375 ref fn_decl,
376 ref body,
377 fn_decl_span: _,
378 fn_arg_span: _,
379 } = **closure;
380 let body = match body.kind {
381 ast::ExprKind::Block(ref block, ref label)
382 if !is_unsafe_block(block)
383 && !context.inside_macro()
384 && is_simple_block(context, block, Some(&body.attrs))
385 && label.is_none() =>
386 {
387 stmt_expr(&block.stmts[0]).unwrap_or(body)
388 }
389 _ => body,
390 };
391 let (prefix, extra_offset) = rewrite_closure_fn_decl(
392 binder,
393 constness,
394 capture_clause,
395 coroutine_kind,
396 movability,
397 fn_decl,
398 body,
399 expr.span,
400 context,
401 shape,
402 )?;
403 if prefix.contains('\n') {
405 return Err(RewriteError::Unknown);
406 }
407
408 let body_shape = shape.offset_left(extra_offset, expr.span)?;
409
410 if is_block_closure_forced(context, body) {
412 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
413 |body_str| {
414 match fn_decl.output {
415 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
416 match rewrite_closure_expr(body, &prefix, context, shape) {
420 Ok(single_line_body_str)
421 if !single_line_body_str.contains('\n') =>
422 {
423 single_line_body_str
424 }
425 _ => body_str,
426 }
427 }
428 _ => body_str,
429 }
430 },
431 );
432 }
433
434 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
437 cond.contains('\n') || cond.len() > body_shape.width
438 });
439 if is_multi_lined_cond {
440 return rewrite_closure_with_block(body, &prefix, context, body_shape);
441 }
442
443 return expr.rewrite_result(context, shape);
445 }
446 Err(RewriteError::Unknown)
447}
448
449pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
451 args.iter()
452 .filter_map(OverflowableItem::to_expr)
453 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
454 .count()
455 > 1
456}
457
458fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
459 if context.inside_macro() {
461 false
462 } else {
463 is_block_closure_forced_inner(expr, context.config.style_edition())
464 }
465}
466
467fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
468 match expr.kind {
469 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
470 ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
471 ast::ExprKind::AddrOf(_, _, ref expr)
472 | ast::ExprKind::Try(ref expr)
473 | ast::ExprKind::Unary(_, ref expr)
474 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
475 _ => false,
476 }
477}
478
479fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
488 match e.kind {
489 ast::ExprKind::If(..)
490 | ast::ExprKind::Match(..)
491 | ast::ExprKind::Block(..)
492 | ast::ExprKind::While(..)
493 | ast::ExprKind::Loop(..)
494 | ast::ExprKind::ForLoop { .. }
495 | ast::ExprKind::TryBlock(..) => false,
496 _ => true,
497 }
498}