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