1use rustc_ast::{ast, ptr};
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
57 .offset_left(extra_offset)
58 .max_width_error(shape.width, span)?;
59
60 if let ast::ExprKind::Block(ref block, _) = body.kind {
61 if block.stmts.is_empty() && !block_contains_comment(context, block) {
63 return body
64 .rewrite_result(context, shape)
65 .map(|s| format!("{} {}", prefix, s));
66 }
67
68 let result = match fn_decl.output {
69 ast::FnRetTy::Default(_) if !context.inside_macro() => {
70 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
71 }
72 _ => Err(RewriteError::Unknown),
73 };
74
75 result.or_else(|_| {
76 rewrite_closure_block(block, &prefix, context, body_shape)
78 })
79 } else {
80 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|_| {
81 rewrite_closure_with_block(body, &prefix, context, body_shape)
84 })
85 }
86}
87
88fn try_rewrite_without_block(
89 expr: &ast::Expr,
90 prefix: &str,
91 context: &RewriteContext<'_>,
92 shape: Shape,
93 body_shape: Shape,
94) -> RewriteResult {
95 let expr = get_inner_expr(expr, prefix, context);
96
97 if is_block_closure_forced(context, expr) {
98 rewrite_closure_with_block(expr, prefix, context, shape)
99 } else {
100 rewrite_closure_expr(expr, prefix, context, body_shape)
101 }
102}
103
104fn get_inner_expr<'a>(
105 expr: &'a ast::Expr,
106 prefix: &str,
107 context: &RewriteContext<'_>,
108) -> &'a ast::Expr {
109 if let ast::ExprKind::Block(ref block, _) = expr.kind {
110 if !needs_block(block, prefix, context) {
111 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
114 return get_inner_expr(expr, prefix, context);
115 }
116 }
117 }
118
119 expr
120}
121
122fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
124 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
125 !get_attrs_from_stmt(first_stmt).is_empty()
126 });
127
128 is_unsafe_block(block)
129 || block.stmts.len() > 1
130 || has_attributes
131 || block_contains_comment(context, block)
132 || prefix.contains('\n')
133}
134
135fn veto_block(e: &ast::Expr) -> bool {
136 match e.kind {
137 ast::ExprKind::Call(..)
138 | ast::ExprKind::Binary(..)
139 | ast::ExprKind::Cast(..)
140 | ast::ExprKind::Type(..)
141 | ast::ExprKind::Assign(..)
142 | ast::ExprKind::AssignOp(..)
143 | ast::ExprKind::Field(..)
144 | ast::ExprKind::Index(..)
145 | ast::ExprKind::Range(..)
146 | ast::ExprKind::Try(..) => true,
147 _ => false,
148 }
149}
150
151fn rewrite_closure_with_block(
154 body: &ast::Expr,
155 prefix: &str,
156 context: &RewriteContext<'_>,
157 shape: Shape,
158) -> RewriteResult {
159 let left_most = left_most_sub_expr(body);
160 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
161 if veto_block {
162 return Err(RewriteError::Unknown);
163 }
164
165 let block = ast::Block {
166 stmts: thin_vec![ast::Stmt {
167 id: ast::NodeId::root(),
168 kind: ast::StmtKind::Expr(ptr::P(body.clone())),
169 span: body.span,
170 }],
171 id: ast::NodeId::root(),
172 rules: ast::BlockCheckMode::Default,
173 tokens: None,
174 span: body
175 .attrs
176 .first()
177 .map(|attr| attr.span.to(body.span))
178 .unwrap_or(body.span),
179 could_be_bare_literal: false,
180 };
181 let block = crate::expr::rewrite_block_with_visitor(
182 context,
183 "",
184 &block,
185 Some(&body.attrs),
186 None,
187 shape,
188 false,
189 )?;
190 Ok(format!("{prefix} {block}"))
191}
192
193fn rewrite_closure_expr(
195 expr: &ast::Expr,
196 prefix: &str,
197 context: &RewriteContext<'_>,
198 shape: Shape,
199) -> RewriteResult {
200 fn allow_multi_line(expr: &ast::Expr) -> bool {
201 match expr.kind {
202 ast::ExprKind::Match(..)
203 | ast::ExprKind::Gen(..)
204 | ast::ExprKind::Block(..)
205 | ast::ExprKind::TryBlock(..)
206 | ast::ExprKind::Loop(..)
207 | ast::ExprKind::Struct(..) => true,
208
209 ast::ExprKind::AddrOf(_, _, ref expr)
210 | ast::ExprKind::Try(ref expr)
211 | ast::ExprKind::Unary(_, ref expr)
212 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
213
214 _ => false,
215 }
216 }
217
218 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
221 || context.config.force_multiline_blocks();
222 expr.rewrite_result(context, shape)
223 .and_then(|rw| {
224 if veto_multiline && rw.contains('\n') {
225 Err(RewriteError::Unknown)
226 } else {
227 Ok(rw)
228 }
229 })
230 .map(|rw| format!("{} {}", prefix, rw))
231}
232
233fn rewrite_closure_block(
235 block: &ast::Block,
236 prefix: &str,
237 context: &RewriteContext<'_>,
238 shape: Shape,
239) -> RewriteResult {
240 Ok(format!(
241 "{} {}",
242 prefix,
243 block.rewrite_result(context, shape)?
244 ))
245}
246
247fn rewrite_closure_fn_decl(
249 binder: &ast::ClosureBinder,
250 constness: ast::Const,
251 capture: ast::CaptureBy,
252 coroutine_kind: &Option<ast::CoroutineKind>,
253 movability: ast::Movability,
254 fn_decl: &ast::FnDecl,
255 body: &ast::Expr,
256 span: Span,
257 context: &RewriteContext<'_>,
258 shape: Shape,
259) -> Result<(String, usize), RewriteError> {
260 let binder = match binder {
261 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
262 "for<> ".to_owned()
263 }
264 ast::ClosureBinder::For { generic_params, .. } => {
265 let lifetime_str =
266 rewrite_bound_params(context, shape, generic_params).unknown_error()?;
267 format!("for<{lifetime_str}> ")
268 }
269 ast::ClosureBinder::NotPresent => "".to_owned(),
270 };
271
272 let const_ = if matches!(constness, ast::Const::Yes(_)) {
273 "const "
274 } else {
275 ""
276 };
277
278 let immovable = if movability == ast::Movability::Static {
279 "static "
280 } else {
281 ""
282 };
283 let coro = match coroutine_kind {
284 Some(ast::CoroutineKind::Async { .. }) => "async ",
285 Some(ast::CoroutineKind::Gen { .. }) => "gen ",
286 Some(ast::CoroutineKind::AsyncGen { .. }) => "async gen ",
287 None => "",
288 };
289 let mover = if matches!(capture, ast::CaptureBy::Value { .. }) {
290 "move "
291 } else {
292 ""
293 };
294 let nested_shape = shape
297 .shrink_left(binder.len() + const_.len() + immovable.len() + coro.len() + mover.len())
298 .and_then(|shape| shape.sub_width(4))
299 .max_width_error(shape.width, span)?;
300
301 let param_offset = nested_shape.indent + 1;
303 let param_shape = nested_shape
304 .offset_left(1)
305 .max_width_error(nested_shape.width, span)?
306 .visual_indent(0);
307 let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
308
309 let param_items = itemize_list(
310 context.snippet_provider,
311 fn_decl.inputs.iter(),
312 "|",
313 ",",
314 |param| span_lo_for_param(param),
315 |param| span_hi_for_param(context, param),
316 |param| param.rewrite_result(context, param_shape),
317 context.snippet_provider.span_after(span, "|"),
318 body.span.lo(),
319 false,
320 );
321 let item_vec = param_items.collect::<Vec<_>>();
322 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
324 let tactic = definitive_tactic(
325 &item_vec,
326 ListTactic::HorizontalVertical,
327 Separator::Comma,
328 horizontal_budget,
329 );
330 let param_shape = match tactic {
331 DefinitiveListTactic::Horizontal => param_shape
332 .sub_width(ret_str.len() + 1)
333 .max_width_error(param_shape.width, 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}{mover}|{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 if let ast::ExprKind::Closure(ref closure) = expr.kind {
366 let ast::Closure {
367 ref binder,
368 constness,
369 capture_clause,
370 ref coroutine_kind,
371 movability,
372 ref fn_decl,
373 ref body,
374 fn_decl_span: _,
375 fn_arg_span: _,
376 } = **closure;
377 let body = match body.kind {
378 ast::ExprKind::Block(ref block, _)
379 if !is_unsafe_block(block)
380 && !context.inside_macro()
381 && is_simple_block(context, block, Some(&body.attrs)) =>
382 {
383 stmt_expr(&block.stmts[0]).unwrap_or(body)
384 }
385 _ => body,
386 };
387 let (prefix, extra_offset) = rewrite_closure_fn_decl(
388 binder,
389 constness,
390 capture_clause,
391 coroutine_kind,
392 movability,
393 fn_decl,
394 body,
395 expr.span,
396 context,
397 shape,
398 )?;
399 if prefix.contains('\n') {
401 return Err(RewriteError::Unknown);
402 }
403
404 let body_shape = shape
405 .offset_left(extra_offset)
406 .max_width_error(shape.width, expr.span)?;
407
408 if is_block_closure_forced(context, body) {
410 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
411 |body_str| {
412 match fn_decl.output {
413 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
414 match rewrite_closure_expr(body, &prefix, context, shape) {
418 Ok(single_line_body_str)
419 if !single_line_body_str.contains('\n') =>
420 {
421 single_line_body_str
422 }
423 _ => body_str,
424 }
425 }
426 _ => body_str,
427 }
428 },
429 );
430 }
431
432 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
435 cond.contains('\n') || cond.len() > body_shape.width
436 });
437 if is_multi_lined_cond {
438 return rewrite_closure_with_block(body, &prefix, context, body_shape);
439 }
440
441 return expr.rewrite_result(context, shape);
443 }
444 Err(RewriteError::Unknown)
445}
446
447pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
449 args.iter()
450 .filter_map(OverflowableItem::to_expr)
451 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
452 .count()
453 > 1
454}
455
456fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
457 if context.inside_macro() {
459 false
460 } else {
461 is_block_closure_forced_inner(expr, context.config.style_edition())
462 }
463}
464
465fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
466 match expr.kind {
467 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
468 ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
469 ast::ExprKind::AddrOf(_, _, ref expr)
470 | ast::ExprKind::Try(ref expr)
471 | ast::ExprKind::Unary(_, ref expr)
472 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
473 _ => false,
474 }
475}
476
477fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
486 match e.kind {
487 ast::ExprKind::If(..)
488 | ast::ExprKind::Match(..)
489 | ast::ExprKind::Block(..)
490 | ast::ExprKind::While(..)
491 | ast::ExprKind::Loop(..)
492 | ast::ExprKind::ForLoop { .. }
493 | ast::ExprKind::TryBlock(..) => false,
494 _ => true,
495 }
496}