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, format_coro, 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_marker: &Option<ast::CoroutineMarker>,
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_marker,
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_marker: &Option<ast::CoroutineMarker>,
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 = coroutine_marker.map_or_default(format_coro);
291 let capture_str = match capture {
292 ast::CaptureBy::Value { .. } => "move ",
293 ast::CaptureBy::Use { .. } => "use ",
294 ast::CaptureBy::Ref => "",
295 };
296 let offset = binder.len() + const_.len() + immovable.len() + coro.len() + capture_str.len();
299 let nested_shape = shape.shrink_left(offset, span)?.sub_width(4, span)?;
300
301 let param_offset = nested_shape.indent + 1;
303 let param_shape = nested_shape.offset_left(1, span)?.visual_indent(0);
304 let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
305
306 let param_items = itemize_list(
307 context.snippet_provider,
308 fn_decl.inputs.iter(),
309 "|",
310 ",",
311 |param| span_lo_for_param(param),
312 |param| span_hi_for_param(context, param),
313 |param| param.rewrite_result(context, param_shape),
314 context.snippet_provider.span_after(span, "|"),
315 body.span.lo(),
316 false,
317 );
318 let item_vec = param_items.collect::<Vec<_>>();
319 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
321 let tactic = definitive_tactic(
322 &item_vec,
323 ListTactic::HorizontalVertical,
324 Separator::Comma,
325 horizontal_budget,
326 );
327 let param_shape = match tactic {
328 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1, span)?,
329 _ => param_shape,
330 };
331
332 let fmt = ListFormatting::new(param_shape, context.config)
333 .tactic(tactic)
334 .preserve_newline(true);
335 let list_str = write_list(&item_vec, &fmt)?;
336 let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|");
337
338 if !ret_str.is_empty() {
339 if prefix.contains('\n') {
340 prefix.push('\n');
341 prefix.push_str(¶m_offset.to_string(context.config));
342 } else {
343 prefix.push(' ');
344 }
345 prefix.push_str(&ret_str);
346 }
347 let extra_offset = last_line_width(&prefix) + 1;
349
350 Ok((prefix, extra_offset))
351}
352
353pub(crate) fn rewrite_last_closure(
356 context: &RewriteContext<'_>,
357 expr: &ast::Expr,
358 shape: Shape,
359) -> RewriteResult {
360 debug!("rewrite_last_closure {:?}", expr);
361
362 if let ast::ExprKind::Closure(ref closure) = expr.kind {
363 let ast::Closure {
364 ref binder,
365 constness,
366 capture_clause,
367 ref coroutine_marker,
368 movability,
369 ref fn_decl,
370 ref body,
371 fn_decl_span: _,
372 fn_arg_span: _,
373 } = **closure;
374 let body = match body.kind {
375 ast::ExprKind::Block(ref block, ref label)
376 if !is_unsafe_block(block)
377 && !context.inside_macro()
378 && is_simple_block(context, block, Some(&body.attrs))
379 && label.is_none() =>
380 {
381 stmt_expr(&block.stmts[0]).unwrap_or(body)
382 }
383 _ => body,
384 };
385 let (prefix, extra_offset) = rewrite_closure_fn_decl(
386 binder,
387 constness,
388 capture_clause,
389 coroutine_marker,
390 movability,
391 fn_decl,
392 body,
393 expr.span,
394 context,
395 shape,
396 )?;
397 if prefix.contains('\n') {
399 return Err(RewriteError::Unknown);
400 }
401
402 let body_shape = shape.offset_left(extra_offset, expr.span)?;
403
404 if is_block_closure_forced(context, body) {
406 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
407 |body_str| {
408 match fn_decl.output {
409 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
410 match rewrite_closure_expr(body, &prefix, context, shape) {
414 Ok(single_line_body_str)
415 if !single_line_body_str.contains('\n') =>
416 {
417 single_line_body_str
418 }
419 _ => body_str,
420 }
421 }
422 _ => body_str,
423 }
424 },
425 );
426 }
427
428 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
431 cond.contains('\n') || cond.len() > body_shape.width
432 });
433 if is_multi_lined_cond {
434 return rewrite_closure_with_block(body, &prefix, context, body_shape);
435 }
436
437 return expr.rewrite_result(context, shape);
439 }
440 Err(RewriteError::Unknown)
441}
442
443pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
445 args.iter()
446 .filter_map(OverflowableItem::to_expr)
447 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
448 .count()
449 > 1
450}
451
452fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
453 if context.inside_macro() {
455 false
456 } else {
457 is_block_closure_forced_inner(expr, context.config.style_edition())
458 }
459}
460
461fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
462 match expr.kind {
463 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
464 ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
465 ast::ExprKind::AddrOf(_, _, ref expr)
466 | ast::ExprKind::Try(ref expr)
467 | ast::ExprKind::Unary(_, ref expr)
468 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
469 _ => false,
470 }
471}
472
473fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
482 match e.kind {
483 ast::ExprKind::If(..)
484 | ast::ExprKind::Match(..)
485 | ast::ExprKind::Block(..)
486 | ast::ExprKind::While(..)
487 | ast::ExprKind::Loop(..)
488 | ast::ExprKind::ForLoop { .. }
489 | ast::ExprKind::TryBlock(..) => false,
490 _ => true,
491 }
492}